It's equivalent to user = user || User.new
.
This relies on the short-circuiting behavior of the ||
operator. If the left side of the expression is true, then it doesn't matter what the right side will be, the overall expression will be true, so the operator "short-circuits" and stops evaluating. And rather than returning a boolean "true", the ||
operator returns the last value that it evaluated.
So, ||=
is useful for assigning a default value. If user
has a value, then user || User.new
evaluates to user
otherwise it evaluates to User.new
which is the default value.
An equivalent block would be:
if user
user = user
else
user = User.new
end