哈希的 Ruby 数组意外行为



我试图创建一个哈希数组,我已经在这里找到了一些很好的解决方案:

在 ruby 中创建哈希数组

然而,在我自己尝试时,我发现了一些我不理解的行为。

在 IRB 中创建哈希数组:

array_hashes = Array.new(7, Hash.new)

现在,在尝试将键、值对分配给数组时:

array_hashes[1]["hello"] = 200

我在控制台中得到了以下输出:

=>[{"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}]
相同的键,值在所有数组元素

中重复,当我尝试将另一个键,值分配给单个数组元素时,结果相似

array_hashes[3]["world"] = 300
=>[{"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}] 

谁能解释一下原因,特别是为什么即使在分配给单个元素时,哈希值也会在所有数组元素中重复。谢谢!

使用的Ruby版本:1.9.3,在Windows 7和OS X Yosemite上试用

重复此操作是因为此代码的作用:

array_hashes = Array.new(7, Hash.new)

是这样的:

hash = Hash.new
array_hashes = [hash, hash, hash, hash, hash, hash, hash]

所以它是数组中包含 7 次的同一对象。

但你想做的是:

array_hashes = Array.new(7) { Hash.new }

最新更新