An auto-vivifying hash is a hash that lets you create sub-hashes automatically. This means that the following code becomes possible:
def cnh # silly name "create nested hash"
Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
end
my_hash = cnh
my_hash[1][2][3] = 4
my_hash # => { 1 => { 2 => { 3 =>4 } } }
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
Tags: ruby








careful! These DO NOT work as they do in perl.
How -do- they work in Perl ?