Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Range#max

() -> Elem
() { (Elem a, Elem b) -> ::Integer } -> Elem
(::Integer n) -> ::Array[Elem]
(::Integer n) { (Elem a, Elem b) -> ::Integer } -> ::Array[Elem]
max → object
max(n) → array
max {|a, b| ... } → object
max(n) {|a, b| ... } → array

Returns the maximum value in self, using method <=> or a given block for comparison.

With no argument and no block given, returns the maximum-valued element of self.

Example
(1..4).max     # => 4
('a'..'d').max # => "d"
(-4..-1).max   # => -1

With non-negative integer argument n given, and no block given, returns the n maximum-valued elements of self in an array:

Example
(1..4).max(2)     # => [4, 3]
('a'..'d').max(2) # => ["d", "c"]
(-4..-1).max(2)   # => [-1, -2]
(1..4).max(50)    # => [4, 3, 2, 1]

If a block is given, it is called:

  • First, with the first two element of self.

  • Then, sequentially, with the so-far maximum value and the next element of self.

To illustrate:

Example
(1..4).max {|a, b| p [a, b]; a <=> b } # => 4

Output:

Example
[2, 1]
[3, 2]
[4, 3]

With no argument and a block given, returns the return value of the last call to the block:

Example
(1..4).max {|a, b| -(a <=> b) } # => 1

With non-negative integer argument n given, and a block given, returns the return values of the last n calls to the block in an array:

Example
(1..4).max(2) {|a, b| -(a <=> b) }  # => [1, 2]
(1..4).max(50) {|a, b| -(a <=> b) } # => [1, 2, 3, 4]

Returns an empty array if n is zero:

Example
(1..4).max(0)                      # => []
(1..4).max(0) {|a, b| -(a <=> b) } # => []

Returns nil or an empty array if:

  • The begin value of the range is larger than the end value:

    Example
    (4..1).max                         # => nil
    (4..1).max(2)                      # => []
    (4..1).max {|a, b| -(a <=> b) }    # => nil
    (4..1).max(2) {|a, b| -(a <=> b) } # => []
    
  • The begin value of an exclusive range is equal to the end value:

    Example
    (1...1).max                          # => nil
    (1...1).max(2)                       # => []
    (1...1).max  {|a, b| -(a <=> b) }    # => nil
    (1...1).max(2)  {|a, b| -(a <=> b) } # => []
    

Raises an exception if either:

  • self is a endless range: (1..).

  • A block is given and self is a beginless range.

Related: Range#min, Range#minmax.

See also #last #member? #inspect #min also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0