Ruby logical operator

I don't know what matters here.

a = 24
b = 60
comp1 = a > 42 or b == 60
comp1 # => false
comp2 = (a > 42 or b == 60)
comp2 # => true

      

Can anyone explain what is happening and why the return values โ€‹โ€‹are different?

+3


source to share


3 answers


This has to do with the strength of operator binding, as operators are applied in a very specific order .

or

very loose, it has the lowest priority. The operator is ||

very strong, on the contrary. Notice how this table ||

precedes =

but or

appears after? This has consequences.

In your example:

comp1 = a > 42 or b == 60

      

This is how Ruby interprets it:



(comp1 = (a > 42)) or (b == 60)

      

So the whole statement returns true

, but gets comp1

assigned false

because it doesn't capture the whole thing.

So, to fix this, just use the strong version of the binding:

comp1 = a > 42 || b == 60
# => true

      

+3


source


This is all related to operator priority. or

has a lower priority than =

, therefore

comp1 = a > 42 or b == 60

      

performed as



(comp1 = a > 42) or (b == 60)

      

You need to enforce the parenthesis precedence. Or be a good ruby โ€‹โ€‹coder and never use and/or

(use &&

/ instead ||

)

* never if you don't know what you are doing. Rule of thumb: & / || for logical operations and / or for control flow.

+3


source


In Ruby, the assignment to ( =

) takes precedence over the written statement or

, so the first line is interpreted like this:

(comp1 = a > 42) or (b == 60)

      

This means that comp1

a value is being assigned a > 42

, which is obviously false. The parenthesis in the second expression fixes the problem.

In general, in Ruby, you use ||

instead or

and also &&

instead of and

.

+1


source







All Articles