Hash#fetch with confidence

May 5, 2013 Abhijit Hiremagalur

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

About the Author

Biography

More Content by Abhijit Hiremagalur
Previous
Sencha Touch BDD – Part 3 – Testing Views and Mocking Stores
Sencha Touch BDD – Part 3 – Testing Views and Mocking Stores

Sencha Touch BDD tl;dr A multi-part series of articles on how to test Sencha Touch applications. It uses Ja...

Next
Getting context in a retro
Getting context in a retro

An agile retrospective is a safe space. We can reflect on the week, think through our victories and defeats...

Enter curious. Exit smarter.

Learn More