views:

1359

answers:

2

What is the Ruby spaceship operator? Is the operator implemented by any other languages?

+24  A: 

Perl was 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 it returns -1

if a = b it returns 0

if a > b it returns 1

It's useful for sorting an array.

ttony21
Exactly. I think of it as a very elegant version of Java's Comparable.
Mike Reedell
analog in c# is IComparable.CompareTo
Sergey Mirvoda
+7  A: 

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.

gnovice