labs ruby

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, would you rather your application 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