Ruby 'or' vs '||'

Possible duplicate:
Difference between "and" and && in Ruby?
Ruby: the difference between || and 'or'

I had this code (something like this)

foo = nil or 4

where I would like to foobe either the first value (maybe nil) or the default value of 4. When I tested in irb, the result was what I expected. Stupid to me, I did not check the value foolater. After some time, I began to notice some errors in my code, and I did not find the problem until I checked the value fooback in irb, which was unexpected, nilinstead of the expected 4.

What is the story about orvs ||? Should they work as a replacement? Are there some warnings when using orinstead ||?

+5
source share
3 answers

The problem here is priority. orhas a lower priority than ||. So your first statement evaluates

(x = nil) or 4

The result of the expression 4(so you thought that it works correctly in irb), but xis assigned nilbecause it orhas a lower priority than =.

The version ||does what you want:

x = (nil || 4)
+12
source

or , || = - , or. || , = .

+4

or has a (very) lower priority.

+2
source

All Articles