-1

I have a simple question about the meaning of a symbol (I think). What's the mean of ||= in ruby? I have a code snippet that say:

... ||= [nil]

Is as "<<" ? ordinary method?

tckmn
  • 57,719
  • 27
  • 114
  • 156
Howarto
  • 124
  • 1
  • 8
  • Please close for my duplicate finding and not the other one; the duplicate I linked to provides much more depth and focus about the specific operation in answers. – user2246674 Jul 19 '13 at 23:40
  • See also [What does `||=` mean in Ruby?](http://stackoverflow.com/questions/995593/what-does-or-equals-mean-in-ruby). – Andrew Marshall Jul 20 '13 at 01:21

1 Answers1

4
x ||= y

means (almost) the same thing as

x = x || y

(it only evaluates x once, though.)

It is used mostly for checking if a variable is falsy (nil or false), and if so, setting it to a default value.

tckmn
  • 57,719
  • 27
  • 114
  • 156
  • 2
    It is not strictly equivalent in Ruby (although it is in JavaScript). See http://stackoverflow.com/a/2505285/2246674 which explains the better approximation. – user2246674 Jul 19 '13 at 23:31
  • 1
    It actually behaves like `x || x = y`, though most of the times that won't make any difference. See http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html – Doodad Jul 19 '13 at 23:58