Alf Steed
Alf Steed

Reputation: 149

Conditional evaluation of a conditional evaluation

What might be a more succinct, rubyesque way of expressing this bit of code?

if should_be_admin
  result = user and user.admin?
else
  result = not user.nil?
end

Upvotes: 0

Views: 39

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110755

result = should_be_admin ? (user and user.admin?) : !!user

or

result = user ? (should_be_admin ? user.admin? : true) : false

!! converts a truthy value to true and a falsy value (nil or false) to false.

Upvotes: 2

Related Questions