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
Written by Marc Anguera Insa
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#