One of my favourite features in Ruby is Hash#default_proc. Let’s see what it can do.
Ever seen code like this?
Stop writing that ✋.
Unless all the values in the collection will be used, the expensive calculations should be delayed until it’s needed.
That looks a lot better already! 🎉
Ruby will evaluate the code in the block when a key is missing. This makes it great tool for these types of lookups, or as a quick in memory cache.
In last weeks post we saw that we can call procs using brackets. When those operations become expensive, we can just wrap it with a Hash without changing our client code.
Great improvement! 👍
How about when you make an API call, and it returns the next and previous values as well, it would be a waste not to use them.
We can populate the Hash based on the previous calls. Sweet! 🎂
Caveat! 🐹
The Hash#default_proc will not be called when using Hash#fetch. This surprised me. 👻