Rails's .try vs Ruby's &. (a.k.a safe navigation)
Rails’s .try vs Ruby’s safe navigation
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
https://dev.to/equivalent/railss-try-vs-rubys-aka-safe-navigation-lp6
Comments
Great trick!
Rails #try is just broken, stopped using it since it’s hiding bugs.
Post a comment