summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-enum-ext/mrblib
diff options
context:
space:
mode:
authorJun Hiroe <[email protected]>2014-03-23 11:41:23 +0900
committerJun Hiroe <[email protected]>2014-03-23 11:41:23 +0900
commit776a680e89701e2d1ea5c6ff3e952fc4b8e72cba (patch)
treeff982d2232dbd8781cf85ad855ce8689f229f852 /mrbgems/mruby-enum-ext/mrblib
parentbbee56f284f3c0df94fe7ec9ad116b266f7f5edd (diff)
downloadmruby-776a680e89701e2d1ea5c6ff3e952fc4b8e72cba.tar.gz
mruby-776a680e89701e2d1ea5c6ff3e952fc4b8e72cba.zip
Enumerable#minmax_by
Diffstat (limited to 'mrbgems/mruby-enum-ext/mrblib')
-rw-r--r--mrbgems/mruby-enum-ext/mrblib/enum.rb39
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 873de1fbc..4b0b87bcc 100644
--- a/mrbgems/mruby-enum-ext/mrblib/enum.rb
+++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb
@@ -374,4 +374,43 @@ module Enumerable
end
[min, max]
end
+
+ ##
+ # call-seq:
+ # enum.minmax_by { |obj| block } -> [min, max]
+ # enum.minmax_by -> an_enumerator
+ #
+ # Returns a two element array containing the objects in
+ # <i>enum</i> that correspond to the minimum and maximum values respectively
+ # from the given block.
+ #
+ # If no block is given, an enumerator is returned instead.
+ #
+ # %w(albatross dog horse).minmax_by { |x| x.length } #=> ["dog", "albatross"]
+
+ def minmax_by(&block)
+ max = nil
+ max_cmp = nil
+ min = nil
+ min_cmp = nil
+ first = true
+
+ self.each do |val|
+ if first
+ max = min = val
+ max_cmp = min_cmp = block.call(val)
+ first = false
+ else
+ if (cmp = block.call(val)) > max_cmp
+ max = val
+ max_cmp = cmp
+ end
+ if (cmp = block.call(val)) < min_cmp
+ min = val
+ min_cmp = cmp
+ end
+ end
+ end
+ [min, max]
+ end
end