Possible Duplicate:
What does ||= mean in Ruby?
I tested like this:
>> a||=3
=> 3
>> a
=> 3
>> a||=b
=> 3
>> b
NameError: undefined local variable or method `b' for main:Object
from (irb):11
Possible Duplicate:
What does ||= mean in Ruby?
I tested like this:
>> a||=3
=> 3
>> a
=> 3
>> a||=b
=> 3
>> b
NameError: undefined local variable or method `b' for main:Object
from (irb):11
It is the shorthand for a logical OR operation. It is equivalent to:
a || a = b
Note: The above code sample has been corrected to reflect the true (if unintuitive) behavior if expanding a ||= b
. Thanks to the people who pointed that out for me. Here is the source
if a
evaluates to true it will remain as is, otherwise b
will be assigned to a
. In ruby nil
evaluates to false
, so you can see how this is useful for lazy loading and default value assignment.