RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

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

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in