Auto-vivifying hashes in Ruby

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:

2 Responses to “Auto-vivifying hashes in Ruby”

  1. swhirsch says:

    careful! These DO NOT work as they do in perl.

  2. Trevoke says:

    How -do- they work in Perl ?

Leave a Reply

You must be logged in to post a comment.