opensoul.org

The Ruby Infinite Hash

@tenderlove shows us ruby magic to create an infinite hash:

>> hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) } 
 => {} 
>> hash['a'] = 1
 => 1 
>> hash['a']
 => 1 
>> hash['b']
 => {} 
>> hash['b']['c']['d']
 => {}

ruby and tidbit December 12, 2010

3 Comments

  1. Christoph Christoph February 3, 2011

    Just like Python’s defaultdict.

    > d = defaultdict(dict)
    > d['a']
    {}
    > d['b']['c'] = 1
    > d['b']['c']
    1

  2. Nick Hoffman Nick Hoffman September 20, 2011

    Slick solution, Brandon. Is there a way to make an existing hash “infinite”?

    The best I’ve found is this:     h = {:foo => {:bar => 'BAR'}}

        h.default_proc = Proc.new do |h, k|
          h[k] = Hash.new(&h.default_proc)
        end

    Unfortunately, the default proc doesn’t apply to nested hashes that already exist:     h[:foo][:doesnt_exist]     => nil

  3. Brandon Keepers Brandon Keepers September 21, 2011

    Nick: Good question. Cleanest solution would probably be some kind of recursive merge.

Post a Comment

Comments use textile. Anonymous comments will be deleted.

My name is Brandon Keepers. I like to build things, usually in Ruby or JavaScript. I work at GitHub and live in Holland, MI.

Popular Posts