Boolean Operators
!
&&
||
!
We use !
to negate/switch a boolean value
!true # false
!false # true
payment_received = false
if !payment_received
send_payment_reminder_email
end
&&
We use &&
to combine two or more boolean values with the "and" rule (aka conjuction)
true && true # true
true && false # false
false && true # false
false && false # false
(See also https://en.wikipedia.org/wiki/Logical_conjunction)
weather = "sunny"
temperature = 27 # celsius
if weather == "sunny" && temperature > 20
puts "You may wear sandals! π‘"
end
We can combine as many booleans as we want.
if condition_1 && condition_2 && condition_3 # ...
puts "This happens only if all conditions were true"
end
Remember: Only if all booleans are true
, the final result is true
.
||
We use ||
to combine two boolean values with the "or" rule (aka disjunction)
true || true # true
true || false # true
false || true # true
false || false # false
(See also https://en.wikipedia.org/wiki/Logical_disjunction)
hour_of_day = 15 # valid: 0 - 23
if hour_of_day < 6 || hour_of_day > 22
puts "You really should go to sleep! ποΈ"
else
puts "Enjoy your day! π"
end
Again, we can combine as many booleans as we want.
if condition_1 || condition_2 || condition_3 # ...
puts "This happens only if 1 or more conditions were true"
end
Remember: If at least one boolean is true
, the final result is true
.
We use parentheses ()
to group boolean results.
travel_mode = 'bicycle' # walking πΆββοΈ or bicycle π΄ββοΈ
distance = 1500 # meters
if (distance > 5000) || (distance > 1000 && travel_mode == 'walking')
puts "You better take something to drink π§ with you".
end
What questions do you have?