Add Enumerable#minmax

This commit is contained in:
Jun Hiroe
2014-03-22 21:52:08 +09:00
parent 7182ef6358
commit 5027aaaf4e
2 changed files with 43 additions and 0 deletions
+37
View File
@@ -335,4 +335,41 @@ 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
max = val
min = val
first = false
else
if block
max = val if block.call(val, max) > 0
min = val if block.call(val, min) < 0
else
max = val if (val <=> max) > 0
min = val if (val <=> min) < 0
end
end
end
[min, max]
end
end
+6
View File
@@ -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