Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

LABS
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

Comments
  1. Matthew Kocher says:

    I’ve switched entirely to using hash fetch anytime a hash index was followed by an || to provide a default. Once you get used to hash.fetch(:the_key, “the default value”) you’ll never want to go back. I picked this up pairing with Jacob Maine, though I remember it being advocated in a blog post around the same time as well.

  2. sam says:

    If you are storing true/false values in a map, you should consider using a set.

  3. Jesse Zhang says:

    In Python, this is the default behavior of the subscript operator: d[key] raises KeyError if key is absent. Users who want to skip through that have to explicitly call d.get(key) to say “give me something or None”.

    It’s funny that Ruby is optimizing for the careless case (assuming operator is intended for the default use case vs method for the expert or so)

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *