0
0
Rubyprogramming~10 mins

Inline if and unless (modifier form) in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Inline if and unless (modifier form)
Start
Evaluate condition
Execute statement
Skip statement
End
The program checks a condition and executes a statement only if the condition is true (for if) or false (for unless), all in one line.
Execution Sample
Ruby
x = 10
puts "x is 10" if x == 10
puts "x is not 5" unless x == 5
Print messages depending on the value of x using inline if and unless.
Execution Table
StepCode LineConditionCondition ResultActionOutput
1x = 10--Assign 10 to x-
2puts "x is 10" if x == 10x == 10truePrint 'x is 10'x is 10
3puts "x is not 5" unless x == 5x == 5falsePrint 'x is not 5'x is not 5
💡 All lines executed; inline conditions controlled printing.
Variable Tracker
VariableStartAfter 1After 2Final
xnil101010
Key Moments - 2 Insights
Why does the second print statement run even though it uses 'unless'?
The 'unless' runs the statement only if the condition is false. Here, x == 5 is false, so it prints. See execution_table row 3.
Can the inline if statement run if the condition is false?
No, the inline if runs the statement only if the condition is true. If false, it skips. See execution_table row 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after step 1?
A10
Bnil
C0
Dundefined
💡 Hint
Check variable_tracker row for x at After 1.
At which step does the condition evaluate to false?
AStep 1
BStep 3
CStep 2
DNone
💡 Hint
Look at the Condition Result column in execution_table.
If x was 5, what would happen at step 3?
AError occurs
BPrint 'x is not 5'
CSkip printing
DPrint 'x is 10'
💡 Hint
Refer to how 'unless' works in execution_table row 3.
Concept Snapshot
Inline if/unless modifier form:
statement if condition
statement unless condition
Executes statement only if condition is true (if) or false (unless).
Good for short conditional actions on one line.
Full Transcript
This example shows how Ruby uses inline if and unless modifiers. First, x is set to 10. Then, the program prints 'x is 10' only if x equals 10, which is true, so it prints. Next, it prints 'x is not 5' unless x equals 5. Since x is 10, not 5, the condition is false, so it prints. The execution table tracks each step, condition, and output. The variable tracker shows x stays 10 throughout. Key moments clarify that 'unless' runs when the condition is false, and 'if' runs when true. The quiz tests understanding of variable values and condition results at each step.