How to Have a Fallback Value Returned from a Ruby Hash Query

Feature thumb gems video thumb

The traditional process for querying a key from a hash in Ruby can lead to unexpected behavior. If you query a key that does not exist in the hash, the output will be nil. So far, so good. However, if you query a key that does exist, but has a nil or false value, you will get nil or false as well. Thankfully Ruby provides a way to query a key and have the method call return an error if the key doesn't exist with the 'fetch' method. Using fetch has become the de facto recommendation when it comes to performing tasks such as looking up environment variables.

However, what happens when you don't want a key lookup to throw an error, but instead return a different value? That's where Ruby's wonderful blocks come in. If you pass the fetch method a block, the block will be envoked if the key is not found, as shown in the examples below: