4

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

I saw a code and an operator I'm unfamiliar with

 @array << {:suffix=> substring, :index => i}
 @array.sort! { |x,y| x[:suffix] <=> y[:suffix]}

I can't do google on it. What does <=> do?

Community
  • 1
  • 1
Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

3 Answers3

5

This is the spaceship operator, it was borrowed from Perl. It is commonly used for sorting, because it returns -1 if left operand is less than right operand, 1 if right operand is greater than the left and returns 0 otherwise.

1 <=> 2 # => -1
2 <=> 1 # => 1
1 <=> 1 # => 0
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
4

It does comparison defined for the particular class. If it is the case that ... < ... is true, it returns -1, if ... == ... is true, then 0, and if ... > ... is true, then 1.

sawa
  • 165,429
  • 45
  • 277
  • 381
1

It's called the spaceship operator.

For the core numeric and string classes, it's a comparison operator that returns -1, 0, or 1.

In theory, a class can define any operator to do anything it wants, but this will be the method that is used when sorting. It may make sense to define <=> for an arbitrary application class if that class will ever need to be ordered.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329