What does the following code mean in Ruby?
||=
Does it have any meaning or reason for the syntax?
It's like lazy instantiation. If the variable is already defined it will take that value instead of creating the value again.
This ruby-lang syntax. The correct answer is to check the ruby-lang documentation. All other explanations obfuscate.
"ruby-lang docs Abbreviated Assignment".
https://docs.ruby-lang.org/en/2.4.0/syntax/assignment_rdoc.html#label-Abbreviated+Assignment
x ||= y
means
if x
has any value leave it alone and do not change the value, otherwise
set x
to y
This is the default assignment notation
for example: x ||= 1
this will check to see if x is nil or not. If x is indeed nil it will then assign it that new value (1 in our example)
more explicit:
if x == nil
x = 1
end
In short, a||=b
means: If a
is undefined, nil or false
, assign b
to a
. Otherwise, keep a
intact.
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.