DEV Community

Tomas Valent
Tomas Valent

Posted on

Rails's .try vs Ruby's &. (a.k.a safe navigation)

Rails #try vs Ruby's &.

User.try(:cat)
# => nil
User.try(:name)
# => "User"
User&.cat
# NoMethodError: undefined method `cat' for User:Class ...
User&.name
#=> "User"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
equivalent profile image
Tomas Valent

Big thanks to varandasi for pointing this out 😇