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

Justin Ethier picture Justin Ethier · May 6, 2009 · Viewed 105.8k times · Source

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

Answer

TonyArra picture TonyArra · May 6, 2009

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.