B
Ben Armstrong
Can anyone explain the following? Our "intuitive" solution (h1) to
creating a constructor for a hash nested within a hash did not work. It
was only after attempting a workaround (h3) and finding that it
performed very poorly that we Googled (h2) a correct solution. But it
is not obvious to us why this more complex constructor is required.
# Unexpected result, h1 hash is empty.
h1=Hash.new(Hash.new(0)) # => {}
h1[1][2]='h1' # => "h1"
h1 # => {}
# Expected result, h2 hash contains nested hash.
h2=Hash.new{|hash,key| hash[key]=Hash.new(0)} # => {}
h2[1][2]='h2' # => "h2"
h2 # => {1=>{2=>"h2"}}
# Expected result but expensive.
h3=Hash.new(Hash.new(0)) # => {}
temp=h3[1].dup # => {}
temp[2]='h3' # => "h3"
h3[1]=temp # => {2=>"h3"}
h3 # => {1=>{2=>"h3"}}
Thanks,
Ben Armstrong
creating a constructor for a hash nested within a hash did not work. It
was only after attempting a workaround (h3) and finding that it
performed very poorly that we Googled (h2) a correct solution. But it
is not obvious to us why this more complex constructor is required.
# Unexpected result, h1 hash is empty.
h1=Hash.new(Hash.new(0)) # => {}
h1[1][2]='h1' # => "h1"
h1 # => {}
# Expected result, h2 hash contains nested hash.
h2=Hash.new{|hash,key| hash[key]=Hash.new(0)} # => {}
h2[1][2]='h2' # => "h2"
h2 # => {1=>{2=>"h2"}}
# Expected result but expensive.
h3=Hash.new(Hash.new(0)) # => {}
temp=h3[1].dup # => {}
temp[2]='h3' # => "h3"
h3[1]=temp # => {2=>"h3"}
h3 # => {1=>{2=>"h3"}}
Thanks,
Ben Armstrong