Skip to content
instance method

Array#<=>

(untyped) -> ::Integer?
self <=> other_array → -1, 0, or 1

Returns -1, 0, or 1 as self is determined to be less than, equal to, or greater than other_array.

Iterates over each index i in (0...self.size):

  • Computes result[i] as self[i] <=> other_array[i].

  • Immediately returns 1 if result[i] is 1:

    Example
    [0, 1, 2] <=> [0, 0, 2] # => 1
    
  • Immediately returns -1 if result[i] is -1:

    Example
    [0, 1, 2] <=> [0, 2, 2] # => -1
    
  • Continues if result[i] is 0.

When every result is 0, returns self.size <=> other_array.size (see Integer#<=>):

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

Note that when other_array is larger than self, its trailing elements do not affect the result:

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

Related: see Methods for Comparing.

See also #<< #== #- #[] also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0