Today I Learned

hashrocket A Hashrocket project

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)

See More #ruby TILs
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.