Understanding ||= syntax - ParkinT/RubyMotion_Life GitHub Wiki
The purpose of ||=
I has been asked many times, what does this (very common) syntactic trick do?
Ben Taylor provides this very succinct description:
To understand better how this construct works, try writing in irb
>> nil || "steve"
=> "steve"
>> "steve" || "john"
=> "steve"
>> "steve" || nil
=> "steve"
>> nil && "steve"
=> nil
>> "steve" && nil
=> nil
>> "steve" && "john"
=> "john"
The construct ||= is shorthand for
>> @blah = @blah || "something"
=> "something"
It's common practice in many programming languages to use boolean operators like this as shorthand for using an if statement.
>> @blah ||= "something"
=> "something"
Can also be written as
>> @blah
=> "something"
>> @blah = "something" unless @blah
=> nil
>> @blah
=> "something"
In more verbose languages it would need to be a full if statement.