0
0
Rubyprogramming~10 mins

Ternary operator usage in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Ternary operator usage
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"none
2N/AN/AN/Aprints "Adult"
💡 Condition evaluated once; status assigned; output printed; program ends.
Variable Tracker
VariableStartAfter Step 1After Step 2 (final)
ageundefined2020
statusundefined"Adult""Adult"
Key Moments - 2 Insights
Why does the ternary operator return a value instead of running code blocks?
The ternary operator is an expression that returns a value immediately based on the condition, as shown in execution_table step 1 where it assigns "Adult" or "Minor" directly to status.
Can the ternary operator replace an if-else statement?
Yes, for simple assignments or returns. The example shows how it replaces if-else by assigning status in one line, making code shorter and clearer.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what value is assigned to status at step 1?
A20
B"Adult"
C"Minor"
Dundefined
💡 Hint
Check the 'Value assigned to status' column in execution_table row 1.
At which step is the output printed?
ANo output is printed
BStep 1
CStep 2
DBefore step 1
💡 Hint
Look at the 'Output' column in execution_table; printing happens after assignment.
If age was 16, what would status be assigned to according to the execution flow?
A"Minor"
B"Adult"
C16
Dundefined
💡 Hint
Refer to the condition in execution_table and how it decides the assigned value.
Concept Snapshot
Ternary operator syntax: condition ? value_if_true : value_if_false
Evaluates condition once.
Returns value_if_true if condition is true.
Returns value_if_false if condition is false.
Used for simple conditional assignments or returns.
Makes code concise and readable.
Full Transcript
The ternary operator in Ruby is a short way to write an if-else that returns a value. It checks a condition, then returns one value if true, another if false. For example, age >= 18 ? "Adult" : "Minor" assigns "Adult" if age is 18 or more, else "Minor". This operator evaluates the condition once, then immediately returns the correct value. It is useful for simple decisions in one line, making code shorter and easier to read. The execution table shows the condition check, the value assigned, and when output is printed. Beginners often wonder why it returns a value and how it replaces if-else. The key is that it is an expression, not a statement, so it fits where a value is needed.