Ruby’s ||= (or equal) operator

Ruby’s ||= operator is a handy way to assign variables if they are not defined yet, but not change the variable if they are already defined. This code shows how to assign the variable x to a value or 5 unless the x variable is already assigned.

x ||= 5

When a variable is already assigned to a value, the ||= operator will not reassign the value.

x ||= 32
# x equals 32
x ||= 45
# x still equals 32

However, the value of a variable will be updated it if is assigned to a value that is falsey (i.e. the ||= operator will reassign a variable that is assigned to nil or false):

z = nil
z ||= "meow"
# z equals "meow"

The ||= operator is also useful for constructing hashes. This code demonstrates how to only reassign the key of a hash to another value if it does not exist:

h = {}
h[:x] ||= "k"
# h equals {:x => "k"}
h[:x] ||= "blah"
# h still equals {:x => "k"}

In most cases, it is fair to think of the ||= operator as:

a = (a || b)

However, it is more accurate to think of ||= as:

a || a = b

Peter Cooper outlines the ||= edge cases in this article.


2 thoughts on “Ruby’s ||= (or equal) operator

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s