0
0
Rubyprogramming~10 mins

Ternary operator in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Ternary operator
Evaluate condition
Yes
Return value if true
End
No
Return value if false
End
The ternary operator checks a condition and returns one value if true, another if false, all in one line.
Execution Sample
Ruby
age = 20
status = age >= 18 ? "Adult" : "Minor"
puts status
This code checks if age is 18 or more, then sets status to 'Adult' or 'Minor' accordingly, and prints it.
Execution Table
StepCondition (age >= 18)ResultValue assigned to statusOutput
120 >= 18true"Adult"
2N/AN/AN/AAdult
💡 Condition evaluated once; since true, 'Adult' assigned and printed; execution ends.
Variable Tracker
VariableStartAfter Step 1After Step 2 (final)
ageundefined2020
statusundefined"Adult""Adult"
Key Moments - 2 Insights
Why does the ternary operator use a question mark and colon?
The question mark separates the condition from the true value, and the colon separates the true value from the false value, as shown in step 1 of the execution_table.
Is the condition evaluated more than once?
No, the condition is evaluated only once at step 1, then the result decides which value is assigned.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 1, what is the condition result?
Atrue
Bfalse
Cundefined
Derror
💡 Hint
Check the 'Condition (age >= 18)' column at step 1 in execution_table.
At which step is the value 'Adult' assigned to status?
AStep 2
BStep 1
CBefore Step 1
DNever assigned
💡 Hint
Look at the 'Value assigned to status' column in execution_table.
If age was 16, what would be the value assigned to status?
Anil
B"Adult"
C"Minor"
Derror
💡 Hint
Think about the ternary operator logic shown in concept_flow and execution_table.
Concept Snapshot
Syntax: condition ? value_if_true : value_if_false
Evaluates condition once.
Returns value_if_true if condition true.
Returns value_if_false if condition false.
Used for simple if-else in one line.
Full Transcript
The ternary operator in Ruby is a short way to write an if-else statement. It first checks a condition. If the condition is true, it returns the first value after the question mark. If false, it returns the value after the colon. In the example, age is 20, which is greater or equal to 18, so the condition is true. The status variable is assigned 'Adult'. Then, the program prints 'Adult'. This operator helps write simple decisions in one line, making code shorter and easier to read.