add Enumerable#each_cons

This commit is contained in:
skandhas
2013-03-22 15:43:30 +08:00
parent b547a7ed2c
commit aacbc39b27
2 changed files with 36 additions and 0 deletions
+31
View File
@@ -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
+5
View File
@@ -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