diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-03-24 23:49:01 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-03-24 23:49:01 +0900 |
| commit | 915b158e89e173b396f8d71aa03584da24386286 (patch) | |
| tree | b86a98cba8213aeceb3e5b9adfae724e06139b1b /mrbgems/mruby-enum-ext/mrblib/enum.rb | |
| parent | aa5920aaaeaf8a59aacb4f0bcba4f11fb2341ce0 (diff) | |
| parent | 381f126f1b6f211730be538522e902e1f3f8ea79 (diff) | |
| download | mruby-915b158e89e173b396f8d71aa03584da24386286.tar.gz mruby-915b158e89e173b396f8d71aa03584da24386286.zip | |
Merge pull request #1933 from suzukaze/add-enum.cycle
Add Enumerable#cycle
Diffstat (limited to 'mrbgems/mruby-enum-ext/mrblib/enum.rb')
| -rw-r--r-- | mrbgems/mruby-enum-ext/mrblib/enum.rb | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb index 127b5dc8c..b492ae9af 100644 --- a/mrbgems/mruby-enum-ext/mrblib/enum.rb +++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb @@ -526,4 +526,38 @@ module Enumerable end self end + + ## + # call-seq: + # enum.cycle(n=nil) { |obj| block } -> nil + # enum.cycle(n=nil) -> an_enumerator + # + # Calls <i>block</i> for each element of <i>enum</i> repeatedly _n_ + # times or forever if none or +nil+ is given. If a non-positive + # number is given or the collection is empty, does nothing. Returns + # +nil+ if the loop has finished without getting interrupted. + # + # Enumerable#cycle saves elements in an internal array so changes + # to <i>enum</i> after the first pass have no effect. + # + # If no block is given, an enumerator is returned instead. + # + # a = ["a", "b", "c"] + # a.cycle { |x| puts x } # print, a, b, c, a, b, c,.. forever. + # a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c. + # + + def cycle(n=nil, &block) + if n == nil + loop {self.each {|val| block.call(val) } } + else + raise TypeError, "expected Integer for 1st argument" unless n.kind_of? Integer + + count = 0 + while count < n + self.each {|val| block.call(val) } + count += 1 + end + end + end end |
