Mastodon

Do or do not. There is no try. Wait, yes there is.

Cruising through Stackoverflow I noticed some syntax that I had never seen before:

@blog.user.try(:username)

Interested, I looked it up. As far as I can tell, it seems that one of the clever folks behind Github posted it as a helpful snippet on his blog.
From there it seems to have made its way into the Rails ActiveSupport library and then into Ruby 1.9 itself. Basically its the same as send except it swallows errors and just returns nil.
An example from the docs:

@person ? @person.name : nil

could be replaced with:

@person.try(:name)

Coolness! I know this will be making its way into my own code shortly. Check out Scott Harvey’s excellent explanation of the try method and also take a look at the documentation here.

Leave a Reply

Discover more from mikewilliamson.dev

Subscribe now to keep reading and get access to the full archive.

Continue reading