【问题标题】:Ruby array of hashes unexpected behaviourRuby 哈希数组意外行为
【发布时间】: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 的文档,它们甚至包含您所询问的确切示例

标签: ruby arrays hash


【解决方案1】:

之所以重复,是因为这段代码的作用:

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 }

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2021-04-25
    相关资源
    最近更新 更多