Commit 776a680e authored by Jun Hiroe's avatar Jun Hiroe

Enumerable#minmax_by

parent bbee56f2
......@@ -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
......@@ -90,3 +90,7 @@ assert("Enumerable#minmax") do
assert_equal ["albatross", "horse"], a.minmax
assert_equal ["dog", "albatross"], a.minmax { |a, b| a.length <=> b.length }
end
assert("Enumerable#minmax_by") do
assert_equal ["dog", "albatross"], %w(albatross dog horse).minmax_by { |x| x.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