diff options
| author | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-03-23 02:13:06 +0900 |
|---|---|---|
| committer | Yukihiro "Matz" Matsumoto <[email protected]> | 2014-03-23 02:13:06 +0900 |
| commit | bbee56f284f3c0df94fe7ec9ad116b266f7f5edd (patch) | |
| tree | 0059304d9c8c383ea559d8a35247145bb1513d3e /mrbgems/mruby-enum-ext/mrblib/enum.rb | |
| parent | 76b2ba886a1472932f37dbe5759725d23be88301 (diff) | |
| parent | 77291f3531fc985065c7c4a93b319e7a44bed179 (diff) | |
| download | mruby-bbee56f284f3c0df94fe7ec9ad116b266f7f5edd.tar.gz mruby-bbee56f284f3c0df94fe7ec9ad116b266f7f5edd.zip | |
Merge pull request #1915 from suzukaze/add-enum.minmax
Add Enumerable#minmax
Diffstat (limited to 'mrbgems/mruby-enum-ext/mrblib/enum.rb')
| -rw-r--r-- | mrbgems/mruby-enum-ext/mrblib/enum.rb | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb index 1849ff4cd..873de1fbc 100644 --- a/mrbgems/mruby-enum-ext/mrblib/enum.rb +++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb @@ -335,4 +335,43 @@ module Enumerable end min end + + ## + # call-seq: + # enum.minmax -> [min, max] + # enum.minmax { |a, b| block } -> [min, max] + # + # Returns two elements array which contains the minimum and the + # maximum value in the enumerable. The first form assumes all + # objects implement <code>Comparable</code>; the second uses the + # block to return <em>a <=> b</em>. + # + # a = %w(albatross dog horse) + # a.minmax #=> ["albatross", "horse"] + # a.minmax { |a, b| a.length <=> b.length } #=> ["dog", "albatross"] + + def minmax(&block) + max = nil + min = nil + first = true + + self.each do |*val| + if first + val = val.__svalue + max = val + min = val + first = false + else + if block + max = val.__svalue if block.call(*val, max) > 0 + min = val.__svalue if block.call(*val, min) < 0 + else + val = val.__svalue + max = val if (val <=> max) > 0 + min = val if (val <=> min) < 0 + end + end + end + [min, max] + end end |
