Why do we use ||= in "Current User"?


In exercise 10 "Current User", why are we using the conditional assignment operator ||= instead of just the plain = in the function :

def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]

I understand how conditional assignment operator works, but I have not wrapped my head around on why it should be used here. (If the user does not exist, wouldn't current_user method just return nil anyway?)

Thank you!


Hello @jwei05,

The method current_user will return the value of current_user if it already exists, and will set the value of current_user to the new_user, and return that value...