Nov 062009
 

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

_____

Update:

Facets has a way of doing an auto-vivifying hash, too! Thanks to Stackoverflow.

# Monkey patching Hash class:
# File lib/core/facets/hash/autonew.rb, line 19
  def self.autonew(*args)
    leet = lambda { |hsh, key| hsh[key] = new( &leet ) }
    new(*args,&leet)
  end

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.

Sweet deal!

  2 Responses to “Auto-vivifying hashes in Ruby”

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

  2. How -do- they work in Perl ?

%d bloggers like this: