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

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


Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1 (true) or 0 (false) depending on whether the arguments are equal or unequal, 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 useful for sorting an array.


The spaceship method is useful when you define it in your own class and include the Comparable module. Your class then gets the >, < , >=, <=, ==, and between? methods for free.

class Card  include Comparable  attr_reader :value  def initialize(value)    @value = value  end  def <=> (other) #1 if self>other; 0 if self==other; -1 if self<other    self.value <=> other.value  endenda = Card.new(7)b = Card.new(10)c = Card.new(8)puts a > b # falseputs c.between?(a,b) # true# Array#sort uses <=> :p [a,b,c].sort # [#<Card:0x0000000242d298 @value=7>, #<Card:0x0000000242d248 @value=8>, #<Card:0x0000000242d270 @value=10>]


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.