Infinite nested hash
Sometimes you want to add a value to a hash in a certain level of a nested structure that might or might not have been initialized before.
You could verify first if every level of the chain exists (data[:foo] ||= {}
, etc.), but it would be interesting to have a way of inserting the whole path to that key at once, like when we create a directory using mkdir -p a/b/c
.
Hash
let us set a default value in case the key was not already present:
The first idea would be to take advantage of that default to initialize the missing key with an empty hash
Ideally, the hash coming from this default would also have the same behaviour:
We need some recursion in which the default value is created with the same code that originated the first hash. For that we can make use of another way of setting a default by passing a Proc
:
We can use this default_proc
to implement the recursion we need:
But this is a bit ugly. We have a nicer syntax to convert a Proc
into a block
:
Usign that we can reduce it to: