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

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
My must-see list from MWRC 2013
My must-see list from MWRC 2013

TL;DR If you watch one talk from Mountain West Ruby 2013, watch Greg Baugues: Devs and Depression. Talks @ ...

×

Subscribe to our Newsletter

!
Thank you!
Error - something went wrong!