Logical Operators Part 3
Part of the Fundamentals section of Coddy's Ruby journey — lesson 19 of 88.
Ruby also provides word-based alternatives for logical operators: and, or, and not. These work similarly to &&, ||, and !, but with one important difference: they have lower precedence.
true and false # false (same as &&)
true or false # true (same as ||)
not true # false (same as !)The lower precedence means these operators are evaluated after assignment. This can lead to unexpected behavior:
result = true && false # result is false
result = true and false # result is true!In the second example, the assignment happens first (result = true), then and false is evaluated but its result is discarded. This is why most Ruby developers prefer &&, ||, and ! for conditions.
The word versions are typically reserved for control flow situations, which you'll encounter later. For now, stick with the symbol operators (&&, ||, !) when writing conditions to avoid surprises.
Challenge
EasyYou are provided with the following variables:
a = true
b = false
c = trueUse the word-based logical operators (and, or, not) to evaluate and display the following expressions, each on a separate line:
a and ba or bnot ba and cb or cnot a
Each output should be either true or false.
Cheat sheet
Ruby provides word-based alternatives for logical operators: and, or, and not. These work similarly to &&, ||, and !, but with lower precedence.
true and false # false
true or false # true
not true # falseThe lower precedence means these operators are evaluated after assignment, which can lead to unexpected behavior:
result = true && false # result is false
result = true and false # result is true!In the second example, the assignment happens first (result = true), then and false is evaluated but its result is discarded.
Most Ruby developers prefer &&, ||, and ! for conditions to avoid surprises. The word versions are typically reserved for control flow situations.
Try it yourself
# Variables are provided for you
a = true
b = false
c = true
# TODO: Write your code below
# Use the word-based logical operators (and, or, not) to evaluate and print each expression
# Each result should be printed on a separate lineThis 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