不能使用数组作为Ruby Hash的默认值?
问题描述:
我正在将项目添加到散列键。我期待得到这样的结构:
I was adding items to a Hash key. I was expecting to get a structure like this:
{
'a' : [1],
'b' : [2, 3, 4]
}
以初始化哈希。
irb> hash = Hash.new([])
=> {}
然后开始使用它:
Then started using it:
irb> hash['a'] << 1
=> [1]
irb> hash['b'] << 2
=> [1, 2]
但事实证明:
But it turns out:
irb> hash
=> {}
答
请改为:
hash = Hash.new{|h, k| h[k] = []}
hash['a'] << 1 # => [1]
hash['b'] << 2 # => [2]
您得到意想不到的结果的原因是您指定了一个空数组作为默认值,但是使用相同的数组;没有复制完成。正确的方法是用一个新的空数组初始化值,就像我的代码一样。
The reason you got your unexpected results is that you specified an empty array as default value, but the same array is used; no copy is done. The right way is to initialize the value with a new empty array, as in my code.