Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator <=> in Ruby [duplicate]

Tags:

ruby

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?

like image 562
Alan Coromano Avatar asked Dec 27 '22 14:12

Alan Coromano


2 Answers

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
like image 177
Sergio Tulentsev Avatar answered Jan 15 '23 00:01

Sergio Tulentsev


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.

like image 22
sawa Avatar answered Jan 15 '23 02:01

sawa