Ruby's precedence
08 April 2009
And you thought and was equal to &&
Have you ever looked at ruby code and said wow, this is so readable, I can use and instead of &&, how cool! Well, not quite. There are differences and pretty important ones to consider. Here, let’s see:
The most basic use of and:
a = "b" and "c"
puts a # => "b"
a = "b" && "c"
p a # => "c"
Notice the precedence issue? With and, the precedence is on the left-hand side while && runs through the entire phrase.
Why is this important? And and && phrases, in practice are generally used in if statements and this would cause a big issue with and statements. Why? (Example time)
1 == 3 and true # false
1 == 3 && true # false
true and 5 == 5 # true
true && 5 == 2 # false
Did you catch that?
true and 5 == 5 # true
It’s clearly not the logic you’d expect when you are using and… One more just to prove my point
"hello" && e = "world" # world + world
"hello" and e = "world" # hello + world
Comments
blog comments powered by Disqus