A Better Way to Query Hash Values in Ruby

Ruby offers a wide variety of solutions for many tasks. In this guide we’re going to explore a more expressive process for querying hashes by leveraging the fetch method.

Summary

Integrate a hash query method that throws an error when asked to query a key that doesn’t exist.

Exercise File

Code File

Exercise Description

The standard hash querying syntax simply returns a nil value when passed a key that doesn’t exist. However this can be confusing because this is the identical behavior to what happens when you query a legitimate key that simply has a nil value. With this in mind, implement a more expressive way to query hashes that will throw an error if the given key does not exist instead of a nil.

Examples

hash = { name: 'Kristine', email: '[email protected]', social: nil }
hash_query(hash, :name) # => 'Kristine'
hash_query(hash, :username) # => Raise KeyError: Key does not exist
hash_query(hash, :social) # => nil

Real World Usage

When working with APIs you will be working with a wide variety of hash values. You will discover that you will be asked to work with collections that contain nil values quite often. If you are using a hash query tool that returns nil for non-existent keys AND for standard nil values, you will waste quite a bit of time trying to figure out the cause of the nil value.

Solution

Can be found on the solutions branch on github.

Jordan Hudgens

view all post
Leave a comment

Please be polite. We appreciate that.

By Daniele Zedda • 18 February

← PREV POST

By Daniele Zedda • 18 February

NEXT POST → 34
Share on