Confused with Ruby's <=> operator
Asked Answered
C

3

7

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

Cartridge answered 20/1, 2011 at 10:46 Comment(0)
D
9

It's called the 'spaceship' operator. More info: What is the Ruby <=> (spaceship) operator? and http://en.wikipedia.org/wiki/Spaceship_operator

Dalury answered 20/1, 2011 at 10:47 Comment(1)
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 }Cartridge
N
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

Northwestwards answered 20/1, 2011 at 10:49 Comment(0)
D
9

It's called the 'spaceship' operator. More info: What is the Ruby <=> (spaceship) operator? and http://en.wikipedia.org/wiki/Spaceship_operator

Dalury answered 20/1, 2011 at 10:47 Comment(1)
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 }Cartridge
S
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)

Shing answered 20/1, 2011 at 15:57 Comment(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?Hypallage

© 2022 - 2024 — McMap. All rights reserved.