An auto-vivifying hash is a hash that lets you create sub-hashes automatically. This means that the following code becomes possible:
This is useful because it reduces the amount of logic in the code. No more "If sub-hash doesn't exist, create it!"
Courtesy of Robert Klemme on www.ruby-forum.com
Facets has a way of doing an auto-vivifying hash, too! Thanks to Stackoverflow.
The standard new method for Hash accepts a block. This block is called in the event of trying to access a key in the Hash which does not exist. The block is passed the Hash itself and the key that was requested (the two parameters) and should return the value that should be returned for the requested key.
You will notice that the
leet lambda does 2 things. It returns a new Hash with
leet itself as the block for handling defaults. This is the behaviour which allows
autonew to work for Hashes of arbitrary depth. It also assigns this new Hash to
hsh[key] so that next time you request the same key you will get the existing Hash rather than a new one being created.
Author Aldric Giacomoni