One of the features that I miss most from my Perl days (and to be honest, there isn’t a whole lot I miss from my Perl days) is autovivification. For more information on what it is, read the wikipedia page on it here.
I stumbled across a post that talks about mimicking Perl’s autovivification here. But I wanted a data structure (specifically a hash) that would be created on demand. So here is a class that creates a recursive hash.
1 2 3 4 5 6 | class RecursiveHash < Hash def initialize recurse_hash = proc { |h,k| h[k] = Hash.new(&recurse_hash) } super(&recurse_hash) end end |
The post Hash Autovivification in Ruby appeared first on Live. Interesting. Stories.