Conditional Assignment in Ruby
Stewart Nguyen
Jan 29, 2022
The a ||= b
is a conditional assignment operator. It’s equivalent to a || a = b
.
If a
is false, i.e.: nil
or false
, then evaluate b
and assign the result to a
.
If a
is truthy, that is, other than nil
and false
, b
will not be evaluated, and a
will remain unchanged.
For example:
a = nil
a ||= 10
a
=> 10
a = 1
a ||= 10
a
=> 1
The gotcha is: if a += b
equals a = a + b
then a ||= b
should be a || a = b
.
It is an entirely incorrect assumption. If a
is not declared beforehand, a || a = b
will result in an undefined variable error.
a || a = 10
Output:
NameError: undefined local variable or method `a'