mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
add Enumerable#each_slice
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user