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
||= do when used like x ||= 10?||= assigns the right side value only if the left side variable is nil or false.x ||= 10x is nil or false, it becomes 10; otherwise, it keeps its current value.a only if a is nil or false?||=, not any variation with single or misplaced symbols.||= correctly as a ||= 5.a = nil b = 20 a ||= 10 b ||= 30 puts a puts b
a ||= 10 when a is nila is nil, a ||= 10 assigns 10 to a.b ||= 30 when b is 20b is already 20 (truthy), b ||= 30 does not change b.count = 0 count ||= 5 puts count
count is 0, which is not nil or false in Ruby (0 is truthy).count ||= 5count is truthy (0), count ||= 5 does not change it.settings = { theme: nil, font_size: 12 }
settings[:theme] ||= 'dark'
settings[:font_size] ||= 14
puts settings[:theme]
puts settings[:font_size]settings[:theme] is nil, settings[:font_size] is 12 (truthy).settings[:theme] ||= 'dark' sets theme to 'dark' because it was nil.settings[:font_size] ||= 14 does not change font_size because 12 is truthy.Pass the test and this pattern moves unknown