Step 11: Logical Operators


If/else gives us a lot more power with our programs, but what if we want to only evaluate a certain statement if more than one statements are true?

my_first_calculation = 16 + 4 + 8
my_second_calculation = 9 - 2


if my_first_calculation < 40 && my_second_calculation == 5
    puts("oooo both of those were true")
else
    puts("okay, one of those was false")
end

Above we introduced the && logical operator. && combines two statements and only evaluates to true if both of them evaluate to true. Let’s look at another example:

my_first_calculation = 16 + 4 + 8
my_second_calculation = 9 - 2


if my_first_calculation < 40 || my_second_calculation == 5
    puts("oooo one of those was true")
else
    puts("okay, both of those were false")
end

This time everything looks the same, but we changed the && operator to the || operator, and now our first check passes. The || operator evaluates to true if one or both of the expressions evaluates to true.