1

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
4

1 Answer 1

5

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.

12
  • thanks dude~ helps me clear the fog~~
    – lkahtz
    Feb 26, 2011 at 4:04
  • 1
    No problem. When you want to know what * does when used in front of an array or in a method call/signature, search for "ruby splat operator". Maybe you already know, but I remember that one taking me a while to find (searching for "*" is not easy). Feb 26, 2011 at 4:07
  • Exactly Ed!! I searched on google and it simply ignore all such operands (even I quote/doublequote them). This is cooool~ Thanks man!!
    – lkahtz
    Feb 26, 2011 at 5:29
  • 1
    This is wrong, as has been discussed a gazillion times already here on StackOverflow, on the Ruby mailing list, and on pretty much every Ruby blog ever created. Feb 26, 2011 at 13:33
  • 1
    @Ed S. - If you browse the duplicates, you'll find A short-circuit (||=) edge case. Summarized: a||=b does not expand to a=a||b but a||a=b. It's a subtle difference but does represent different behavior as described in the article. Feb 28, 2011 at 21:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.