Skip to content

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

instance method

Enumerable#max

enum.max → obj
enum.max { |a, b| block } → obj
enum.max(n) → array
enum.max(n) { |a, b| block } → array

Returns the object in enum with the maximum value. The first form assumes all objects implement <=>; the second uses the block to return a <=> b.

Example
a = %w(albatross dog horse)
a.max                                   #=> "horse"
a.max { |a, b| a.length <=> b.length }  #=> "albatross"

If the n argument is given, maximum n elements are returned as an array, sorted in descending order.

Example
a = %w[albatross dog horse]
a.max(2)                                  #=> ["horse", "dog"]
a.max(2) {|a, b| a.length <=> b.length }  #=> ["albatross", "horse"]
[5, 1, 3, 4, 2].max(3)                    #=> [5, 4, 3]
See also #map #max_by #lazy #member? also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1