||= WAT?

wat-gigantic-duckFirst off, I stole this pic from Greg Pike’s post about Javascript.  Now that the confession is out of the way…

Today at App Academy my pair and I were asked to explain the meaning of Ruby’s “double pipe equals” operator  to our cohorts.  I figured that might be a good topic to post here.

The double pipe equals, which will be referred to as “||=” from now on, is an operator that’s used for conditional assignment.

In a nutshell the||= operator’s usage is something like this:

blah ||= blabbity_blah()

This essentially says: “if blah is false then set it to blabbity_blah(), otherwise leave it set to whatever it was before we started”

Here’s a contrived, but-still-real-code, example lifted (and modified) from Wikibooks: