back

Why setting the default value of a Hash to be a Hash is wrong

A short look at Ruby.

December 31, 2008

  1. boof says:

    I had some fun playing with:

    1
    2
    3
    4
    5
    6
    7
    8
    
      hash_default = proc { |h,k| h[k] = Hash.new(&hash_default) }
      a_hash = Hash.new(&hash_default)
    
      a_hash[:foo] # => {}
      a_hash # => {:foo => {}}
      a_hash[:foo][:bar] # => {}
      a_hash[:foo][:bar][:baz] = 'Yay!'
      a_hash # => {:foo=>{:bar=>{:baz=>"Yay!"}}}
    

  2. Momoro says:

    Boof -- interesting.

    It makes me wonder/understand why the syntax for procs and hashes is so similar.

  3. roland says:

    Yet another nested hash test here:

    Basic Trie data structure in Ruby

    http://snippets.dzone.com/posts/show/5616