What does the following code mean in Ruby?
||=
Does it have any meaning or reason for the syntax?
b = 5
a ||= b
This translates to:
a = a || b
which will be
a = nil || 5
so finally
a = 5
Now if you call this again:
a ||= b
a = a || b
a = 5 || 5
a = 5
b = 6
Now if you call this again:
a ||= b
a = a || b
a = 5 || 6
a = 5
If you observe, b
value will not be assigned to a
. a
will still have 5
.
Its a Memoization Pattern that is being used in Ruby to speed up accessors.
def users
@users ||= User.all
end
This basically translates to:
@users = @users || User.all
So you will make a call to database for the first time you call this method.
Future calls to this method will just return the value of @users
instance variable.