summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-enum-ext/mrblib/enum.rb
diff options
context:
space:
mode:
authorskandhas <[email protected]>2013-03-22 15:43:30 +0800
committerskandhas <[email protected]>2013-03-22 15:43:30 +0800
commitaacbc39b27dcb6697b1463deb86d87ffbfdc64bc (patch)
treeea1efa8ef2f3d7f320d1080ec59d3bb4d90ef0b1 /mrbgems/mruby-enum-ext/mrblib/enum.rb
parentb547a7ed2cc781500a572b3a24fdfba7aed85e40 (diff)
downloadmruby-aacbc39b27dcb6697b1463deb86d87ffbfdc64bc.tar.gz
mruby-aacbc39b27dcb6697b1463deb86d87ffbfdc64bc.zip
add Enumerable#each_cons
Diffstat (limited to 'mrbgems/mruby-enum-ext/mrblib/enum.rb')
-rw-r--r--mrbgems/mruby-enum-ext/mrblib/enum.rb31
1 files changed, 31 insertions, 0 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb
index a9545da98..7116325f7 100644
--- a/mrbgems/mruby-enum-ext/mrblib/enum.rb
+++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb
@@ -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