Hash Autovivification in Ruby

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.

class RecursiveHash < Hash
  def initialize
    recurse_hash = proc { |h,k| h[k] = Hash.new(&recurse_hash) }

Posted in Ruby. Tags: , . No Comments »