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#min_by

min_by {|element| ... } → element
min_by(n) {|element| ... } → array
min_by → enumerator
min_by(n) → enumerator

Returns the elements for which the block returns the minimum values.

With a block given and no argument, returns the element for which the block returns the minimum value:

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

With a block given and positive integer argument n given, returns an array containing the n elements for which the block returns minimum values:

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

Returns an Enumerator if no block is given.

Related: min, minmax, max_by.

See also #min #minmax #member? #minmax_by also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0