Logical Operators Part 2
Part of the Fundamentals section of Coddy's Ruby journey — lesson 17 of 88.
The ! operator (called "not") flips a boolean value to its opposite. If something is true, applying ! makes it false, and vice versa:
logged_in = true
!logged_in # false
is_empty = false
!is_empty # trueThis operator is particularly useful when you want to check if something is NOT the case. For example, instead of checking if a user is logged out, you can check if they're "not logged in":
has_permission = false
!has_permission # true (they do NOT have permission)You can also combine ! with comparison expressions by wrapping the expression in parentheses:
age = 15
!(age >= 18) # true (age is NOT 18 or older)The ! operator is often used to reverse conditions or check for the absence of something, making your logic more readable when you need to express negative conditions.
Challenge
EasyYou are provided with the following variables:
is_raining = true
has_ticket = false
is_member = true
age = 16
balance = 0Use the ! (not) operator to evaluate and display the following expressions, each on a separate line:
- The opposite of
is_raining - The opposite of
has_ticket - The opposite of
is_member - Check if
ageis NOT greater than or equal to18(use!with parentheses) - Check if
balanceis NOT equal to0(use!with parentheses)
Each output should be either true or false.
Cheat sheet
The ! operator (called "not") flips a boolean value to its opposite:
logged_in = true
!logged_in # false
is_empty = false
!is_empty # trueYou can combine ! with comparison expressions by wrapping the expression in parentheses:
age = 15
!(age >= 18) # true (age is NOT 18 or older)Try it yourself
# Variables are already defined for you
is_raining = true
has_ticket = false
is_member = true
age = 16
balance = 0
# TODO: Use the ! (not) operator to evaluate and print each expression
# 1. The opposite of is_raining
# 2. The opposite of has_ticket
# 3. The opposite of is_member
# 4. Check if age is NOT greater than or equal to 18
# 5. Check if balance is NOT equal to 0This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False