1

From what I understand, a ||= 7 means the following: if a has a value, continue using that value, but if it does NOT have one, then set it to 7.

Here is what happens though.

If i have a and b as:

a = true

b = false

then

a ||= b => true

(in my interpretation: since 'a' DOES have a value, it remains that, and does not get equated to 'false' - so far so good.)


However, if i have them switched up like:

a = false

b = true

then a ||= b => true

so in this case my logic does not work, since it should return false, as "since 'a' has a value, it should not be assigned the value of 'b'", which apparently happens here.

Am I missing something?

JJJ
  • 32,902
  • 20
  • 89
  • 102
metrazol
  • 119
  • 1
  • 2
  • 11
  • Good discussion of `||=` (and `&&=`) [here](http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html). Also, note that because `a ||= b` will override any falsy value (like `nil` and `false`), you don't want to use it on variables that can have legitimate values of `false` or `nil`. – Amadan May 22 '15 at 09:15
  • Here is more detail. http://stackoverflow.com/questions/995593/what-does-or-equals-mean-in-ruby – mttr May 22 '15 at 20:00

1 Answers1

7
a ||= b

is equivalent to

a || a = b

this means b value is assigned to a if a is falsy, i.e. false or nil.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91