What is the Ruby <=> (spaceship) operator?

Viewed 124005

What is the Ruby <=> (spaceship) operator? Is the operator implemented by any other languages?

6 Answers

The spaceship operator will return 1, 0, or āˆ’1 depending on the value of the left argument relative to the right argument.

a <=> b :=
  if a < b then return -1
  if a = b then return  0
  if a > b then return  1
  if a and b are not comparable then return nil

It's commonly used for sorting data.

It's also known as the Three-Way Comparison Operator. Perl was likely the first language to use it. Some other languages that support it are Apache Groovy, PHP 7+, and C++20.

It's a general comparison operator. It returns either a -1, 0, or +1 depending on whether its receiver is less than, equal to, or greater than its argument.

Related