7

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

Andrew Grimm
  • 74,534
  • 52
  • 194
  • 322
arscariosus
  • 1,276
  • 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
  • 307,646
  • 55
  • 250
  • 337
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
  • 200,802
  • 40
  • 378
  • 386
  • 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,173
  • 13
  • 46
  • 56
  • 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