I don't know what makes a difference here.
a = 24
b = 60
comp1 = a > 42 or b == 60
comp1 # => false
comp2 = (a > 42 or b == 60)
comp2 # => true
Could someone explain what's going on and why the return values are different?
This is due to the strength of the operator binding, as operators are applied in a very particular order.
or is very loose, it has the lowest priority. The || operator is very strong, the opposite of that. Note how in that table || comes before =, but or comes after? That has implications.
From your example:
comp1 = a > 42 or b == 60
This is how Ruby interprets this:
(comp1 = (a > 42)) or (b == 60)
As such, the entire statement returns true but comp1 is assigned false because it doesn't capture the whole thing.
So to fix that, just use the strong binding version:
comp1 = a > 42 || b == 60
# => true
It has all to do with operator precedence. or has lower priority than =, so
comp1 = a > 42 or b == 60
is executed as
(comp1 = a > 42) or (b == 60)
You need to enforce precedence by parentheses. Or be a good ruby coder and never* use and/or (use &&/|| instead)
* never, unless you know what you're doing. A rule of thumb is: &&/|| for logical operations, and/or - for control flow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With