5

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 ||?

Community
  • 1
  • 1
Sergio Campamá
  • 746
  • 1
  • 7
  • 14
  • Although I agree that the questions are directly related, and have a near identical answer, they are not the same question. If the first one was expanded to compare `or` vs `||` as well as `and` vs `&&`, I'd agree that they were duplicates. – zzzzBov Nov 11 '11 at 20:54
  • Also see http://stackoverflow.com/questions/1434842/is-there-any-wisdom-behind-and-or-operators-in-ruby , http://stackoverflow.com/questions/3904888/why-and-or-behaves-differently-in-rails , &c. – jball Nov 11 '11 at 21:08

3 Answers3

13

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)
Ed S.
  • 122,712
  • 22
  • 185
  • 265
4

or has lower precedence than both || and = - that means assignment is executed before or. While || has higher precedence than = and is executed first.

RocketR
  • 3,626
  • 2
  • 25
  • 38
2

or has (very) lower precedence.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302