5

Possible Duplicate:
What does ||= mean in Ruby?

What does ||= mean in Ruby?

Community
  • 1
  • 1
ben
  • 29,229
  • 42
  • 124
  • 179

3 Answers3

9

It's mainly used as a shortform for initializing a variable to a certain value, if it is not yet set.

Think about the statement as returning x || (x = y). If x has a value (other than false), only the left side of the || will be evalutated (since || short-circuts), and x will be not be reassigned. However, if x is false or nil, the right side will be evaluated, which will set x to y, and y will be returned (the result of an assignment statement is the right-hand side).

See http://dablog.rubypal.com/2008/3/25/a-short-circuit-edge-case for more discussion.

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
  • `x ||= y` acts like `x = y unless x` which (if we assume x and y stand for arbitrary expressions and not necessarily variables) is *not* the same as either `x = x || y` (consider cases where `x = x` is not a no-op) or `x = y if x.nil?` (consider the case where x is false). – sepp2k Sep 27 '10 at 08:11
  • Jorg W Mittag reckons this is incorrect, in [his answer](http://stackoverflow.com/questions/995593/what-does-mean-in-ruby) to the duplicated question. – Andrew Grimm Sep 27 '10 at 10:38
  • This is wrong. Please read http://Ruby-Forum.Com/topic/151660 and the links provided therein. – Jörg W Mittag Sep 27 '10 at 12:46
  • @Jörg et al., I've updated my answer. – Daniel Vandersluis Sep 27 '10 at 17:24
4

x ||= y is often used instead of x = y if x == nil

Nakilon
  • 34,866
  • 14
  • 107
  • 142
3

The idea is the same as with other similar operators (+=, *=, etc):
a ||= b is a = a || b

And this trick is not limited to Ruby only: it goes through many languages with C roots.

edit to repel downvoters.
See one of Jörg's links for more accurate approximation, for example this one.
This is exactly why I don't like Ruby: nothing's ever what it seems.

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181