I am confused with Ruby's <=> operator. How does it differ from == or ===? Any comprehensive examples/use case? Thanks.
Asked
Active
Viewed 7,454 times
3 Answers
14
<=>
is the combined comparison operator. it returns 0 if LHS equals RHS, 1 if LHS is greater than the RHS and -1 if LHS is less than RHs

ghostdog74
- 327,991
- 56
- 259
- 343
9
It's called the 'spaceship' operator. More info: What is the Ruby <=> (spaceship) operator? and http://en.wikipedia.org/wiki/Spaceship_operator
-
how about in this code snippet, this confused me the most. assuming a = [ "d", "a", "e", "c", "b" ] how does this work, exactly? a.sort {|x,y| y <=> x } – arscariosus Jan 20 '11 at 11:02
2
== will NOT work in sort for example
[3,5,6,2,7].sort{|x,y| x <=>y }
== returns Boolean
<=> returns Fixnum (-1,0,1)

c2h2
- 11,911
- 13
- 48
- 60
-
1I'm assuming -1 is the same as false, and 1 is the same as true. But how does it work in this example? – Ka Mok Jul 01 '16 at 23:57