mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
add Enumerable#each_cons
This commit is contained in:
@@ -82,4 +82,35 @@ module Enumerable
|
||||
ary
|
||||
end
|
||||
|
||||
##
|
||||
# call-seq:
|
||||
# enum.each_cons(n) {...} -> nil
|
||||
#
|
||||
# Iterates the given block for each array of consecutive <n>
|
||||
# elements.
|
||||
#
|
||||
# e.g.:
|
||||
# (1..10).each_cons(3) {|a| p a}
|
||||
# # outputs below
|
||||
# [1, 2, 3]
|
||||
# [2, 3, 4]
|
||||
# [3, 4, 5]
|
||||
# [4, 5, 6]
|
||||
# [5, 6, 7]
|
||||
# [6, 7, 8]
|
||||
# [7, 8, 9]
|
||||
# [8, 9, 10]
|
||||
|
||||
def each_cons(n, &block)
|
||||
raise TypeError, "expected Integer for 1st argument" unless n.kind_of? Integer
|
||||
raise ArgumentError, "invalid size" if n <= 0
|
||||
|
||||
ary = []
|
||||
self.each do |e|
|
||||
ary.shift if ary.size == n
|
||||
ary << e
|
||||
block.call(ary.dup) if ary.size == n
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
@@ -23,3 +23,8 @@ assert("Enumerable#take_while") do
|
||||
assert_equal a.take_while {|i| i < 3 }, [1, 2]
|
||||
end
|
||||
|
||||
assert("Enumrable#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
|
||||
|
||||
Reference in New Issue
Block a user