Commit bbee56f2 authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #1915 from suzukaze/add-enum.minmax

Add Enumerable#minmax
parents 76b2ba88 77291f35
......@@ -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
......@@ -84,3 +84,9 @@ end
assert("Enumerable#min_by") do
assert_equal "dog", %w[albatross dog horse].min_by { |x| x.length }
end
assert("Enumerable#minmax") do
a = %w(albatross dog horse)
assert_equal ["albatross", "horse"], a.minmax
assert_equal ["dog", "albatross"], a.minmax { |a, b| a.length <=> b.length }
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment