Using Hashes as Caches

One of the coolest features of Ruby’s Hash class is that you can customize how it behaves when it can’t find a key. Stupid example:

One particularly useful application of this feature is to use a Hash as a cache for some slow operation. Here’s a snippet from Firetower, where a Hash is being used as a table of user accounts. If an unknown user ID is requested, the Hash makes a web service call to retrieve the requested data, stores it away, and returns it.