-2

I recently saw a code which looks something like this

  @a ||=
          if x
            x/2
          else
            2 * x

What is the use of ||=

rubyman
  • 255
  • 2
  • 3
  • 9
  • 1
    You can check this [Stackoverflow answer](http://stackoverflow.com/questions/995593/what-does-or-equals-mean-in-ruby) out. I found it quite informative. – Stephen C Feb 19 '16 at 19:42
  • 1
    Forget the `||=`, how is your example supposed to execute `2 * x` if `x` is `false` or `nil`? – pjs Feb 19 '16 at 19:44

1 Answers1

1

It means execute the assignment if the variable is falsey.

So if @a is falsey (e.g. nil or false) the code afterwards is run and it's return value assigned to @a

This works because a OR statement is true, if the first operand is true and therefore does not need be further executed.

It's equivalent to the longer expression:

unless @a
  if x
    @a = x/2
  else
    @a = 2*x # though this line is kind of weird if x is falsey^^
  end
end
dfherr
  • 1,633
  • 11
  • 24