Skip to content

Commit

Permalink
add Enumerable#each_slice
Browse files Browse the repository at this point in the history
  • Loading branch information
skandhas committed Mar 22, 2013
1 parent aacbc39 commit 39a553d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
29 changes: 29 additions & 0 deletions mrbgems/mruby-enum-ext/mrblib/enum.rb
Expand Up @@ -113,4 +113,33 @@ def each_cons(n, &block)
end
end

##
# call-seq:
# enum.each_slice(n) {...} -> nil
#
# Iterates the given block for each slice of <n> elements.
#
# e.g.:
# (1..10).each_slice(3) {|a| p a}
# # outputs below
# [1, 2, 3]
# [4, 5, 6]
# [7, 8, 9]
# [10]

def each_slice(n, &block)
raise TypeError, "expected Integer for 1st argument" unless n.kind_of? Integer
raise ArgumentError, "invalid slice size" if n <= 0

ary = []
self.each do |e|
ary << e
if ary.size == n
block.call(ary)
ary = []
end
end
block.call(ary) unless ary.empty?
end

end
9 changes: 8 additions & 1 deletion mrbgems/mruby-enum-ext/test/enum.rb
Expand Up @@ -23,8 +23,15 @@
assert_equal a.take_while {|i| i < 3 }, [1, 2]
end

assert("Enumrable#each_cons") do
assert("Enumerable#each_cons") do
a = []
(1..5).each_cons(3){|e| a << e}
assert_equal a, [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
end

assert("Enumerable#each_slice") do
a = []
(1..10).each_slice(3){|e| a << e}
assert_equal a, [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
end

0 comments on commit 39a553d

Please sign in to comment.