What is the Ruby <=>
(spaceship) operator? Is the operator implemented by any other languages?
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.