Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Enumerable#max_by

() -> ::Enumerator[E, E?]
() { (E arg0) -> (::Comparable | ::Array[untyped]) } -> E?
(::Integer arg0) -> ::Enumerator[E, ::Array[E]]
(::Integer arg0) { (E arg0) -> (::Comparable | ::Array[untyped]) } -> ::Array[E]
max_by {|element| ... } → element
max_by(n) {|element| ... } → array
max_by → enumerator
max_by(n) → enumerator

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

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

Example
(1..4).max_by {|element| -element }                    # => 1
%w[a b c d].max_by {|element| -element.ord }           # => "a"
{foo: 0, bar: 1, baz: 2}.max_by {|key, value| -value } # => [:foo, 0]
[].max_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 maximum values:

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

Returns an Enumerator if no block is given.

Related: max, minmax, min_by.

See also #max #member? #map #min also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0