Need to understand hash of hashes in ruby [closed]

2019-09-23 10:02发布

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.

标签: ruby hash
1条回答
该账号已被封号
2楼-- · 2019-09-23 10:25

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
# => {}
查看更多
登录 后发表回答