Confused by this method – can someone please explain it to me?
def current_user
@current_user ||= (login_from_session || login_from_cookie) unless @current_user == false
end
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It says:
@current_userif@current_useris already set (the||=part)login_from_sessionand assign the result to@current_usernilorfalse, call the method/helperlogin_from_cookieand assign the result to@current_user@current_userinstance variableIt could be rewritten to be more explicit in this way
This is the power (and the beauty) of ruby expressiveness. Remember that in Ruby only
nilandfalseevaluate to boolean false in if/else statements and||,&&operatorsOther hints to understand better, in ruby you have the following rules:
The return value of any function is the last expression evaluated for the function, so
is the same of
The if/unless statement at the end of an expression is the same of a if/unless statement, so
is the same of
The
||=operator is a shortcut forCombine all these rules and you’ve the method explained.