I often find myself wanting to find hash keys that are nested within a given hash. This is common when getting API responses, as they usually give back a ton of information. The way to handle these giant hashes usually involves manually traversing each level:
Or even worse, when the response hash contains arrays as values to hash keys:
This requires you to know exactly how the hash is structured, which is a pain. What if you could just specify the key you wanted to find, and the work of traversing the hash could be done for you?
Here is a solution I came up with:
This is works for some cases, but we’re not quite done yet. What if the key you’re looking for is not unique? You could get a response hash that looks like this:
If you want to get the value key for address, it won’t work. The value of telephone will be found first, and the method will return.
To fix this, I added an optional nested_key argument, so you can define the parent key first.
Now you can find the value key within address by writing deep_find(response_hash, "address", nested_key: "value").
To use deep_find in any Ruby class, just include the DeepFind module: