7

I am confused with Ruby's <=> operator. How does it differ from == or ===? Any comprehensive examples/use case? Thanks.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
arscariosus
  • 1,326
  • 2
  • 13
  • 19

3 Answers3

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

Community
  • 1
  • 1
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • 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
  • 1
    I'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