Understanding order of operations in boolean operators


#1

Link to exercise:
https://www.codecademy.com/courses/learn-ruby/lessons/control-flow-in-ruby/exercises/billions-of-booleans?action=lesson_resume&link_content_target=interstitial_lesson

So I don’t think my code is behaving incorrectly, I could just use some clarification on the order that things seem to be executing in. My main confusion is: is the reverse operator !() processed before objects within parenthesis?

My issue is this:
test_1 should be true.
My code:

test_1 = !(3 < 5 || 5 < 3 && 33 < 12)

My line of reasoning with this is as follows:

3 < 5 == true so I can discard the "5 < 3" segment because of the either/or || operator.
Then to the right of the and operator: 33 < 12 == false.

So in my mind the entire statement is false because the and operator requires both sides to be correct, and the right side is blatantly false.

Then by adding !() around the entire equation I expected to get an answer of true since the code inside returns a value of false, but I appear to be receiving an answer of false, and hence my confusion…

Could anyone shine some light on this?


#2

Ruby processes operators in a specific order: && comes before ||, and since the && is run first, it goes as follows:

!(3 < 5 OR 5 < 3 AND 33 < 12)
!(3 < 5 OR FALSE)
!(TRUE)
FALSE

To properly order things, it’s important to use parentheses around things that you want processed before anything else.


#3

That’s super interesting. :open_mouth:
Thanks!

I can tell I’ll need to play with this some more outside of the sim to fully understand it, but at least it’s definitely intriguing to say the least. :grinning:


#4

In the precedence table found in
https://stackoverflow.com/questions/21060234/ruby-operator-precedence-table
you can see

highest precedence first

2 L Y  < <= >= >              ordering    (high precedence)
2 L N  &&                     boolean AND
2 L N  ||                     boolean OR
1 R N  not                    boolean NOT (low precedence)

thus

!(3 < 5 || 5 < 3 && 33 < 12) 
!( true || false &&  false ) <-- Step 1
!( true ||      false      ) <-- Step 2
!(     true                ) <-- Step 3
  false                       <-- Result

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.