Ruby has an or-equals operator that allows a value to be assigned to a variable if and only if that variable evaluates to either
||= # this is the operator that achieves this.
this operator with the double pipes representing or and the equals sign representing assigning of a value. You may think it represents something like this:
x = x || y
this above example is not correct. The or-equals operator actually represents this:
x || x = y
x evaluates to
x is assigned the value of
y, and left unchanged otherwise.
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 what ever reason there is no email for this user. You might write something like this:
if user_email.nil? user_email = "firstname.lastname@example.org" end
Using the or-equals operator we can cut this entire chunk of code, providing clean, clear control and functionality.
user_email ||= "email@example.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