Last Updated: February 25, 2016
·
3.982K
· markets

Ruby hashes and "try"

try method is an Object extension from ActiveSupport. It's useful in some cases (ie. chained calls). It's usually used to call a method on an object if it exists, or return nil if it doesn’t, rather than raising an exception (NoMethodError):

>> object.try(:nonexistent_method)
=> nil

Usage with hashes is less intuitive:

>> hash = { a: 1, b: 2 }
=> {:a=>1, :b=>2}
>> hash.try(:a)
=> nil
>> hash.try(:[], :a)
=> 1

1 Response
Add your response

Interesting article related with "try" usage and software design: http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/

over 1 year ago ·