3

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

Danny
  • 5,945
  • 4
  • 32
  • 52
  • Your second block is not strictly correct. You actually have something like `x = false or true; p x # => false`, right? It's when the assignment happens that is confusing you. In short, assignment is just another operator, it is processed *before* `or` and *after* `||`. Usually you want `||`, but the semantics of `or` are still useful from time-to-time. – Neil Slater Jan 26 '14 at 13:08

3 Answers3

4

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
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
3

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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1
x = ((complex expression evaluating to false) or (complex expression evaluating to true))
# or
x = (complex expression evaluating to false) || (complex expression evaluating to true)

in this expression

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

here is actually two of them. First is assignment

x = (complex expression evaluating to false)

and if assignment will return false second expression will be evaluated. But x will be false even if second expression is true.

This is happenning because of or has less priority then =

fl00r
  • 82,987
  • 33
  • 217
  • 237