I have a protected method in my application contoller
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
I was wondering what ||=
means?
I've been trying to search and find out, but to no avail.
I have a protected method in my application contoller
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
I was wondering what ||=
means?
I've been trying to search and find out, but to no avail.
Basically, a ||= b
means assign b to a if a is null or undefined or false (i.e. false-ish value in ruby)
, it is similar to a = b unless a
, except it will always evaluate to the final value of a
(whereas a = b unless a
would result in nil
if a
was true-ish).
This is part of Ruby.
If @current_user
is nil or false, it will be set to User.find_by_id(session[:user_id])
Notice the parallels with a += b
, which is equivalent to a = a + b
.
So a ||= b
is equivalent to a = a || b
. As others have mentioned, this is the same as a = b unless a
.
In ruby 'a ||= b' is called "or - equal" operator. It is a short way of saying if a has a boolean value of true(if it is neither false or nil) it has the value of a. If not it has the value of b.
Basically, a ||= b means assign b to a if a is null or undefined or false (i.e. false-ish value in ruby), it is a shortcut to a = b unless a.
share|edit answered Sep 26 '11 at 14:48
Romain 6,9711330
In addition to this answer here`s an example -
arr = nil || []
arr0 ||= []
arr <=> arr0 *#=> 0*
This means arr
expression and arr0
expression are equal.
Hope this helps to understand better ||=
operator.