tags:

views:

130

answers:

2

I was under the impression that || and or were synonymous.

Setting variable with or does not hold value; why?

>> test = nil or true
=> true
>> test
=> nil

>> test = false or true
=> true
>> test
=> false

Works 'as expected' with ||

>> test = nil || true
=> true
>> test
=> true
+15  A: 

or has lower precedence than =.

test = nil or true

is the same as

(test = nil) or true

which is true, while setting test to nil.

|| has higher precedence than =.

test = nil || true

is the same as

test = (nil || true)

which is true, while setting test to true.

Jonathan Feinberg
...which is why we wouldn't write a piece of code like this, or if we did, we would always use brackets to make it clear what's going on.
Mark
Thank you, this makes perfect sense.
Corban Brook
Jörg W Mittag
+1  A: 

Same between and and &&. I was once bited by this gotcha, then I realize that although and is more readable than &&, that does not mean it always more suitable.

>> f = true && false
=> false
>> f
=> false
>> f = true and false
=> false
>> f
=> true
>>
pierr