0
0
Rubyprogramming~10 mins

Conditional assignment (||=) in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Conditional assignment (||=)
Start
Check variable truthiness
Yes|No
Skip assignment
End
Check if variable is truthy; if not, assign new value; otherwise, keep original.
Execution Sample
Ruby
x = nil
x ||= 10
x ||= 20
puts x
Assign 10 to x if x is nil or false; then try to assign 20 but skip because x is truthy; finally print x.
Execution Table
StepVariable x beforeCondition (x truthy?)ActionVariable x afterOutput
1nilNoAssign 10 to x10
210YesSkip assignment10
310-Print x1010
💡 After step 2, x is truthy so no more assignments; step 3 prints final value.
Variable Tracker
VariableStartAfter 1After 2After 3 (final)
xnil101010
Key Moments - 2 Insights
Why doesn't x change to 20 in the second conditional assignment?
Because at step 2 in the execution_table, x is already truthy (10), so the ||= operator skips assigning 20.
What values count as falsey for ||= in Ruby?
Only nil and false are falsey; all other values, including 0 and empty strings, are truthy, so ||= skips assignment.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x after step 1?
Anil
B10
C20
Dfalse
💡 Hint
Check the 'Variable x after' column in row for step 1.
At which step does the condition 'x truthy?' become true?
AStep 1
BStep 3
CStep 2
DNever
💡 Hint
Look at the 'Condition (x truthy?)' column in the execution_table.
If x started as false instead of nil, what would be the value of x after step 1?
A10
Bnil
Cfalse
D20
💡 Hint
Recall that ||= assigns when variable is false or nil; see step 1 action.
Concept Snapshot
Conditional assignment (||=) in Ruby:
- Syntax: variable ||= value
- Assigns value only if variable is nil or false
- Keeps original if variable is truthy
- Useful for setting defaults
- Example: x ||= 10 sets x to 10 if x is nil or false
Full Transcript
This visual trace shows how Ruby's conditional assignment operator ||= works. We start with x as nil. At step 1, since x is nil (falsey), x gets assigned 10. At step 2, x is now 10 (truthy), so the assignment to 20 is skipped. Finally, at step 3, printing x outputs 10. The key point is ||= only assigns if the variable is nil or false, otherwise it keeps the current value. This helps set default values without overwriting existing ones.