需要了解哈希中哈希的散列 [英] Need to understand hash of hashes in ruby

查看:164
本文介绍了需要了解哈希中哈希的散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Hash.new {| hash,key | hash [key] = Hash.new} 

但是我不明白key和value是否被转换为哈希值。如果你定义了 hash ,那么可以有人解释我对此的简要解释。 >这样,ruby将散列中的每个键的默认值设置为新的散列并保存。



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


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.

解决方案

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

这篇关于需要了解哈希中哈希的散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆