Spaceship Operator (<=>) (Ruby)
The spaceship operator <=> compares two values and returns -1, 0, or 1 (or nil if not comparable). It's the basis for sorting and for the Comparable mixin.
Ruby
a <=> b returns -1 when a < b, 0 when they're equal, and 1 when a > b — a three-way comparison in one operator. sort and sort_by use it under the hood, so defining <=> on your class makes its instances sortable.
It's also the single method the Comparable module needs: include Comparable and define <=>, and you get <, <=, ==, >, >=, between?, and clamp for free. This is the idiomatic way to make a custom class fully comparable.
When two values can't be meaningfully compared, <=> returns nil. For custom types, implement <=> by comparing the attribute(s) that define order, often by delegating to the <=> of a tuple of fields.
Syntax
a <=> b # => -1, 0, or 1Examples
Ruby
puts (1 <=> 2)
puts (2 <=> 2)
puts ("b" <=> "a")
puts [3, 1, 2].sort { |a, b| b <=> a }.inspectOutput:
-1
0
1
[3, 2, 1]