&& Using the Ternary Operator
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 logical and
except that it has a higher precedence than and
. 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 calling has_password?
on nil
. Another way to do this would be to use try
, e.g.:
user.try(:has_password?, submitted_password) ? user : nil
It simply checks if user
has any value before applying the method has_password?
on it.
精彩评论