Need to understand hash of hashes in ruby [closed]

2019-09-23 09:51发布

问题:

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
# => {}


标签: ruby hash