User.try(:cat)
# => nil
User.try(:name)
# => "User"
User&.cat
# NoMethodError: undefined method `cat' for User:Class ...
User&.name
#=> "User"
chain
User.try(:name).try(:cat)
# => nil
User.try(:cat).try(:name)
User&.name&.cat
# NoMethodError: undefined method `cat' for "User":String
User&.cat&.name
# NoMethodError: undefined method `cat' for User:Class
Keep in mind long chains are Law of Demeter violations
Acording to Alexander Budchanov's article.
Safe navigation (
&.
) is about 7 times faster than method try() for successful navigation and 3 times faster for unsuccessful.
Top comments (1)
Big thanks to varandasi for pointing this out 😇