Hey I was following Michael Hartl’s railstutorial when I stumbled upon this chunk of code.
Does anyone have an idea what the “user &&” is used for by the ternary operator?
Here’s the code:
def self.authenticate(email, submitted_password)
user = find_by_email(email)
user && user.has_password?(submitted_password) ? user : nil
end
&&is a logicalandexcept that it has a higher precedence thanand. So the statement just says if user isn’t nil and user has that password then return user, else return nil.In Ruby, the second part of a logical and isn’t executed if the first part is false. So the purpose here is to make sure there’s a user before calling
has_password?on it, thus preventing the error of callinghas_password?onnil. Another way to do this would be to usetry, e.g.: