Hash Autovivification in Ruby

By eric

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

Follow My Travels

Buy My Book

Archives

  • 2014
  • 2013
  • 2012
  • 2011
  • 2010
  • 2009
  • 2008
  • 2007
  • 2006

writing