I am confused with Ruby's <=> operator. How does it differ from == or ===? Any comprehensive examples/use case? Thanks.
Confused with Ruby's <=> operator
Asked Answered
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 } –
Cartridge
<=>
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
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 } –
Cartridge
== will NOT work in sort for example
[3,5,6,2,7].sort{|x,y| x <=>y }
== returns Boolean
<=> returns Fixnum (-1,0,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.