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

Array#<=>

array <=> other_array → -1, 0, or 1

Returns -1, 0, or 1 as self is less than, equal to, or greater than other_array. For each index i in self, evaluates result = self[i] <=> other_array[i].

Returns -1 if any result is -1:

Example
[0, 1, 2] <=> [0, 1, 3] # => -1

Returns 1 if any result is 1:

Example
[0, 1, 2] <=> [0, 1, 1] # => 1

When all results are zero:

  • Returns -1 if array is smaller than other_array:

    Example
    [0, 1, 2] <=> [0, 1, 2, 3] # => -1
    
  • Returns 1 if array is larger than other_array:

    Example
    [0, 1, 2] <=> [0, 1] # => 1
    
  • Returns 0 if array and other_array are the same size:

    Example
    [0, 1, 2] <=> [0, 1, 2] # => 0
    
See also #<< #== #- #[] also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1