Hash#fetch with confidence
Hash#fetch
is stricter about key presence than Hash#[]
{}[:foo]
=> nil
{}.fetch(:foo)
KeyError: key not found: :foo
If you forget to set an ENV
variable that your code relies on, would you rather it fail late or immediately?
ENV['TWITTER_OAUTH_TOKEN']
=> nil
ENV.fetch('TWITTER_OAUTH_TOKEN')
KeyError: key not found
It's especially interesting when a key with a truthy default is explicitly set to a falsy value:
options = {on: false}
@on = options[:on] || true
=> true # yikes, ever fallen into this trap?
@on = options.fetch(:on, true)
=> false
Written by Abhijit Hiremagalur
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#