问题
I came to know that we can create hash of hashes as below:
Hash.new{|hash, key| hash[key] = Hash.new}
But I dont understand whether the key and value getting converted as hash. Can someone explain me in brief about this.
回答1:
If you define hash this way, ruby set the default value on every key in hash to new hash and save it.
sample
h = Hash.new{|hash, key| hash[key] = Hash.new}
h[:foo]
# => {}
p h
# => {:foo=>{}}
insted of define only default value
h = Hash.new({})
h[:foo]
# => {}
p h
# => {}
来源:https://stackoverflow.com/questions/37679425/need-to-understand-hash-of-hashes-in-ruby