What does the following code mean in Ruby?
||=
Does it have any meaning or reason for the syntax?
Suppose a = 2
and b = 3
THEN, a ||= b
will be resulted to a
's value i.e. 2
.
As when a evaluates to some value not resulted to false
or nil
.. That's why it ll
not evaluate b
's value.
Now Suppose a = nil
and b = 3
.
Then a ||= b
will be resulted to 3
i.e. b
's value.
As it first try to evaluates a's value which resulted to nil
.. so it evaluated b
's value.
The best example used in ror app is :
#To get currently logged in iser
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
# Make current_user available in templates as a helper
helper_method :current_user
Where, User.find_by_id(session[:user_id])
is fired if and only if @current_user
is not initialized before.