【发布时间】:2014-12-10 17:37:39
【问题描述】:
我试图创建一个哈希数组,我已经在这里找到了一些很好的解决方案:
Creating array of hashes in 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::new的文档,它们甚至包含您所询问的确切示例。