As I’ve previously talked about, Hashes of Hashes are weird to work with. In the previous post about Captain Planet, I showed how to select, filter and manipulate 2D hashes and arrays but ultimately concluded that a hash of hashes is both weird and unnecessary (most of the time).
If you can control the data, inline your key into the hash data and make an Array of Hashes. It’s really where it belongs. If you don’t, you’ll find yourself doing a few extra iterations or work. Below you’ll see a simple example of the two data structures.
In this case of an array of hashes, the data is easier to manipulate with array operations and filters. But before talking about matching on arrays of hashes, I want to talk about matching on dates.
So comparisons with dates work like you might expect. But fuzzy matches do not. Take this example. Is Marty in between Doc Brown and the distant future? The answer should be true.
We use a Range (x..y) object to make a date range. Then we can use === to check if we get a match.
But wait, === on Date is different than === on Range. The method === on Date checks to see if it’s the same Date whereas === on Range checks to see if the argument is within the range. So if you flip it, it returns true.
So what we did in the middle there was flatten the hash of hashes into an array of hashes by merging the key with the ‘data’ part of the hash. Hopefully that makes sense.