我想用嵌套的默认值创建一个新的哈希。我以为应该是
h = Hash.new(count: 0, rating: 0)
所以我可以做类似的事情
h['a'][:count] += 1
h['a'][:rating] += 1
依此类推。但是,当我在控制台中尝试时,它看起来像这样:
2.3.1 :046 > h = Hash.new(count: 0, rating: 0)
=> {}
2.3.1 :047 > h["a"]
=> {:count=>0, :rating=>0}
2.3.1 :048 > h["a"][:count]
=> 0
2.3.1 :049 > h["a"][:count] += 1
=> 1
2.3.1 :050 > h["b"][:count] += 1
=> 2
2.3.1 :051 > h
=> {}
所以我的问题是:
h["b"][:count] += 1
返回2而不是1?提前感谢!
使用块创建哈希,如下所示:
h = Hash.new { |h,k| h[k] = { count: 0, rating: 0 } }
然后:
2.6.3 :012 > h
=> {}
2.6.3 :013 > h['a'][:count] = 5
=> 5
2.6.3 :015 > h
=> {"a"=>{:count=>5, :rating=>0}}