Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#minmax_by

minmax_by {|element| ... } → [minimum, maximum]
minmax_by → enumerator

Returns a 2-element array containing the elements for which the block returns minimum and maximum values:

Example
(1..4).minmax_by {|element| -element }
# => [4, 1]
%w[a b c d].minmax_by {|element| -element.ord }
# => ["d", "a"]
{foo: 0, bar: 1, baz: 2}.minmax_by {|key, value| -value }
# => [[:baz, 2], [:foo, 0]]
[].minmax_by {|element| -element }
# => [nil, nil]

Returns an Enumerator if no block is given.

Related: max_by, minmax, min_by.

See also #minmax #none? #min_by #one? also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0