||= What?

 

Saying computer languages are complicated is an understatement. Double Pipe equals sounds like gibberish. Even looking at the operators can leave you scratching your head. ||=  Or Equals is a “conditional assignment operator”.

You would think a ||= b to be:

a = a || b But that isn’t the case. ||= behaviors more like this.

a || a = b

When a equals falsey (i.e. nil or false)  the value of b will be assigned to a .

a = nil

b = 'thai_takeout'

a ||=b

a #=> 'thai_takeout'

 

When you  change the value of to equal something other than falsey.

a = 'leftovers'

b = 'thai_takeout'

a ||=b

a # =>  "leftovers'

Using boolean values true and false

a ||= true

a # => true

When a is assigned false

a = false

a ||= true

a # => true

*Remember when a equals false or nil the value of b will be assigned to a.

Here are some helpful resources for additional reading on ||=:

DABlog a short-circuit

StackOverflow -What does ||= mean in Ruby?

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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