Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's 'or' vs '||' [duplicate]

Tags:

ruby

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

like image 304
Sergio Campamá Avatar asked Nov 11 '11 20:11

Sergio Campamá


3 Answers

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)
like image 198
Ed S. Avatar answered Oct 02 '22 03:10

Ed S.


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

like image 29
RocketR Avatar answered Oct 02 '22 04:10

RocketR


or has (very) lower precedence.

like image 36
Dave Newton Avatar answered Oct 02 '22 02:10

Dave Newton