Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby logical operator [duplicate]

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?

like image 403
Edzzn Avatar asked Sep 13 '26 23:09

Edzzn


2 Answers

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
like image 177
tadman Avatar answered Sep 15 '26 14:09

tadman


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.

like image 32
Sergio Tulentsev Avatar answered Sep 15 '26 14:09

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!