Need help with or (||) in Ruby


#1


Could someone please explain to me in a bit more detail how || works, specifically in situations like this:


true || !(true || false)

!true && (!true || 100 != 5**2)

(3 < 4 || false) && (false || true)

I got those right, but it was by pure guesswork after looking at them for 20ish minutes.


#2

|| is the symbol for the logical OR operator.

T || T  => T
T || F  => T
F || T  => T
F || T  => F

&& is the symbol for the logical AND operator.

T && T  => T
T && F  => F
F && T  => F
F && F  => F

! is the symbof for the logical NOT operator. It works behind the scenes on the operand converting it first to a boolean, then negates it.

!true  => false
!false => true

!("A") => !true  => false
!(0)   => !false => true

As in algebra there is an order or operations known as precedence. The order of operation is NOT, AND, OR. When there are brackets, we evaluate inside the brackets first, then work outwards.

Eg.

true || !(true || false)

Start with the brackets...

true || false  => true

Then apply the NOT

! true  => false

Finally the OR

true || false  => true

Eg.

!true && (!true || 100 != 5**2)

Start with the brackets...

!true || 100 != 5 ** 2

false || 100 != 25

false || true  => true

Now evaluate the expression,

!true && true

false && true  => false

Eg.

(3 < 4 || false) && (false || true)

Start with the brackets, left and right

3 < 4 || false

true || false  => true  # left operand

false || true  => true  # right operand

Finally,

true && true  => true

#3

THANK YOU! It would be nice if the entire first section you mentioned, as well as the precedence, was mentioned BEFORE they teach you the operators. It would've made much more sense.


#4

Actually, I thought the Ruby section was pretty well written. Is there no mention of precedence in the track? You may be right. The course was written by a former moderator, Eric Weinstein, more than three years ago. Most people who take the track breeze through it, but there are still a number of newbies to programming who jump into that track first and run into difficulty.


#5

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