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.
x = nil x ||= 10 x ||= 20 puts x
| Step | Variable x before | Condition (x truthy?) | Action | Variable x after | Output |
|---|---|---|---|---|---|
| 1 | nil | No | Assign 10 to x | 10 | |
| 2 | 10 | Yes | Skip assignment | 10 | |
| 3 | 10 | - | Print x | 10 | 10 |
| Variable | Start | After 1 | After 2 | After 3 (final) |
|---|---|---|---|---|
| x | nil | 10 | 10 | 10 |
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