Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

Ruby #try Operator

In Rails, there’s a #try method that will attempt to call a method on an object. If the caller is not nil, it will return the result of the “tried” method. If the caller is nil, try will return nil:

chicken.try(:farm) # => "delicious" (assuming chicken is an object whose #farm function returns "delicious")

# otherwise

chicken.try(:farm) => nil

Ruby 2.3.0 introduced the Safe Navigation Operator &. that is a shorthand for the try method.

chicken&.farm # => "delicious" (assuming chicken is an object whose #farm function returns "delicious")

# otherwise

chicken&.farm => nil

(Shouts out to Dorian)

Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.