add Enumerable#each_slice

This commit is contained in:
skandhas
2013-03-22 15:56:25 +08:00
parent aacbc39b27
commit 39a553d44e
2 changed files with 37 additions and 1 deletions
+29
View File
@@ -113,4 +113,33 @@ module Enumerable
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
+8 -1
View File
@@ -23,8 +23,15 @@ assert("Enumerable#take_while") do
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