Last Updated: February 25, 2016
·
512
· hiremaga

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