Need to understand hash of hashes in ruby [closed]

不想你离开。 提交于 2019-12-26 09:18:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!