Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

false or true != true or false != true || false [duplicate]

Tags:

ruby

This took me quite some time today, and I finaly found the cause, but still don't get the logic

x = (complex expression evaluating to false) or (complex expression evaluating to true)

x => false

Very strange... It turns out, after experimenting that

false or true => false
true or false => true
false || true => true
true || false => true

I guess I've used the "or" operator in hundreds of places in my code, and honestly speaking, I don't trust the "or" anymore...

Can someone please explain the "logic"?

like image 844
Danny Avatar asked Jan 16 '26 18:01

Danny


2 Answers

As per the precedence table or has lower precedence than =. Thus x = true or false will be evaluated as (x = true) or false. But || has higher precedence than =, x = true || false will be evaluated as x = (true || false).

x = false or true
x # => false
x = false || true
x # => true
like image 197
Arup Rakshit Avatar answered Jan 19 '26 19:01

Arup Rakshit


First of all the expressions false or true, true or false, false || true and true || false are all true. If you type them into irb, you will see that.

The reason that your code doesn't work like you expect is the precedence of or versus =. x = y or z is parsed as (x = y) or z, not x = (y or z). With || it's parsed as x = (y || z) because || has higher precedence.

like image 42
sepp2k Avatar answered Jan 19 '26 19:01

sepp2k