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)
Tweet