Ruby Monstas


Boolean Operators

Coverage

  • "not"-Operator !
  • "and"-Operator &&
  • "or"-Operator ||

"not"-Operator !

We use ! to negate/switch a boolean value

!true     # false
!false    # true

"not" Example

payment_received = false

if !payment_received
  send_payment_reminder_email
end

"and"-Operator &&

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)

"and" Example

weather = "sunny"
temperature = 27 # celsius

if weather == "sunny" && temperature > 20
  puts "You may wear sandals! πŸ‘‘"
end

"and" with more than 2

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.

"or"-Operator ||

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)

"or" Example

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

"or" with more than 2

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.

The power of parentheses

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

Additional Resources

Ruby For Beginners: Logical Operators

What questions do you have?