Or-equals (`||=`) conditional assignment
suggest changeRuby has an or-equals operator that allows a value to be assigned to a variable if and only if that variable evaluates to either nil or false.
||= # this is the operator that achieves this.
The double pipe means “or”, and the equals sign assigns. You may think it represents something like this:
x = x || y
The example above is not the whole story. For a variable that is already defined, ||= acts like this:
x || x = y
If x is nil or false, x is assigned y. Otherwise it is left unchanged. ||= can also introduce a new local variable. A bare x || x = y raises NameError when x has never been assigned.
Here is a practical use-case of the or-equals operator. Imagine you have a portion of your code that is expected to send an email to a user. What do you do if, for whatever reason, this user has no email? You might write something like this:
if user_email.nil?
user_email = "error@yourapp.com"
end
||= replaces that check when nil and false are both stand-ins for “missing”:
user_email ||= "error@yourapp.com"
In cases where false is a valid value, care must be taken to not override it accidentally:
has_been_run = false
has_been_run ||= true
#=> true
has_been_run = false
has_been_run = true if has_been_run.nil?
#=> false