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.
orhas lower precedence than does||. So, your first statement evaluates toThe result of the expression is
4(which is why you thought it was working correctly inirb), butxis assignednilbecauseorhas lower precedence than does=.The
||version does what you want: