I recently saw a code which looks something like this
@a ||=
if x
x/2
else
2 * x
What is the use of ||=
I recently saw a code which looks something like this
@a ||=
if x
x/2
else
2 * x
What is the use of ||=
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