问题描述:

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?

网友答案:

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.

网友答案:

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
网友答案:

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.

相关阅读:
Top