Or-EqualsConditional assignment operator

suggest change

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 nil or false.

||= # 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

If x evaluates to nil or false then 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 = "error@yourapp.com"
end

Using the or-equals operator we can cut this entire chunk of code, providing clean, clear control and functionality.

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents