Flashuni
Flashuni

Reputation: 41

&& 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

Upvotes: 0

Views: 3071

Answers (2)

Mori
Mori

Reputation: 27799

&& 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

Upvotes: 7

patapizza
patapizza

Reputation: 2398

It simply checks if user has any value before applying the method has_password? on it.

Upvotes: 1

Related Questions