相关疑难解决方法(0)

使用哈希默认值时出现奇怪的,意外的行为(消失/更改值),例如Hash.new([])

考虑以下代码:

h = Hash.new(0)  # New hash pairs will by default have 0 as values
h[1] += 1  #=> {1=>1}
h[2] += 2  #=> {2=>2}
Run Code Online (Sandbox Code Playgroud)

这一切都很好,但是:

h = Hash.new([])  # Empty array as default value
h[1] <<= 1  #=> {1=>[1]}                  ? Ok
h[2] <<= 2  #=> {1=>[1,2], 2=>[1,2]}      ? Why did `1` change?
h[3] << 3   #=> {1=>[1,2,3], 2=>[1,2,3]}  ? Where is `3`?
Run Code Online (Sandbox Code Playgroud)

在这一点上,我希望哈希是:

{1=>[1], 2=>[2], 3=>[3]}
Run Code Online (Sandbox Code Playgroud)

但它远非如此.发生了什么,我怎样才能得到我期望的行为?

ruby hash

102
推荐指数
2
解决办法
2万
查看次数

如何在Ruby中的Hash中初始化一个数组

我正在尝试初始化一个Hash of Arrays,例如

@my_hash = Hash.new(Array.new)
Run Code Online (Sandbox Code Playgroud)

这样我就可以:

@my_hash["hello"].push("in the street")
=> ["in the street"]
@my_hash["hello"].push("at home")
=> ["in the street", "at home"]
@my_hash["hello"]
=>["in the street", "at home"]
Run Code Online (Sandbox Code Playgroud)

问题是任何新的哈希键也会返回 ["in the street", "at home"]

@my_hash["bye"]
=> ["in the street", "at home"]
@my_hash["xxx"]
=> ["in the street", "at home"]
Run Code Online (Sandbox Code Playgroud)

!!! ???

我怎么做错了什么是初始化Hash of Arrays的正确方法?

ruby arrays hash

34
推荐指数
2
解决办法
2万
查看次数

标签 统计

hash ×2

ruby ×2

arrays ×1