Skip to content

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

instance method

Integer#<=>

(::Integer | ::Rational) -> ::Integer
(untyped) -> ::Integer?
self <=> other → -1, 0, 1, or nil

Compares self and other.

Returns:

  • -1, if self is less than other.

  • 0, if self is equal to other.

  • 1, if self is greater then other.

  • nil, if self and other are incomparable.

Examples:

Example
1 <=> 2              # => -1
1 <=> 1              # => 0
1 <=> 1.0            # => 0
1 <=> Rational(1, 1) # => 0
1 <=> Complex(1, 0)  # => 0
1 <=> 0              # => 1
1 <=> 'foo'          # => nil

Class Integer includes module Comparable, each of whose methods uses Integer#<=> for comparison.

See also #<= #== #<< #=== also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0