Possible Duplicate:
Difference between “and” and && in Ruby?
Ruby: difference between || and 'or'
I had this code (something like this)
foo = nil or 4
where I wanted foo
to be either the first value (could be nil
), or a default 4. When I tested in irb, the output was what I expected it to be. Silly me, I didn't check the value of foo
later. After a while, I started noticing some errors in my code, and I didn't find the problem until I DID check the value of foo
back in irb, which was, oh surprise, nil
instead of the expected 4.
What's the story about or
vs ||
? Are they supposed to work as replacements? Are there some caveats on using or
instead of ||
?
The issue here is precedence. or
has lower precedence than does ||
. So, your first statement evaluates to
(x = nil) or 4
The result of the expression is 4
(which is why you thought it was working correctly in irb
), but x
is assigned nil
because or
has lower precedence than does =
.
The ||
version does what you want:
x = (nil || 4)
or
has lower precedence than both ||
and =
- that means assignment is executed before or
. While ||
has higher precedence than =
and is executed first.
or
has (very) lower precedence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With