diff options
| author | skandhas <[email protected]> | 2013-03-22 15:43:30 +0800 |
|---|---|---|
| committer | skandhas <[email protected]> | 2013-03-22 15:43:30 +0800 |
| commit | aacbc39b27dcb6697b1463deb86d87ffbfdc64bc (patch) | |
| tree | ea1efa8ef2f3d7f320d1080ec59d3bb4d90ef0b1 /mrbgems/mruby-enum-ext/mrblib/enum.rb | |
| parent | b547a7ed2cc781500a572b3a24fdfba7aed85e40 (diff) | |
| download | mruby-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.rb | 31 |
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 |
