相关疑难解决方法(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代码:

h=Hash.new([])
h[0]=:word1    
h[1]=h[1]<<:word2
h[2]=h[2]<<:word3
print "\nHash = "
print h
Run Code Online (Sandbox Code Playgroud)

输出是:

Hash = {0=>:word1, 1=>[:word2, :word3], 2=>[:word2, :word3]}
Run Code Online (Sandbox Code Playgroud)

我原以为有

Hash = {0=>:word1, 1=>[:word2], 2=>[:word3]}
Run Code Online (Sandbox Code Playgroud)

为什么附加第二个哈希元素(数组)?

如何用新数组元素追加第3个哈希的元素?

ruby arrays hashtable

5
推荐指数
1
解决办法
3012
查看次数

Ruby哈希初始化器

哈希初始值设定项:

# this
animals = Hash.new { [] }
animals[:dogs] << :Scooby
animals[:dogs] << :Scrappy
animals[:dogs] << :DynoMutt
animals[:squirrels] << :Rocket
animals[:squirrels] << :Secret
animals #=> {}
# is not the same as this
animals = Hash.new { |_animals, type| _animals[type] = [] }
animals[:dogs] << :Scooby
animals[:dogs] << :Scrappy
animals[:dogs] << :DynoMutt
animals[:squirrels] << :Rocket
animals[:squirrels] << :Secret
animals #=> {:squirrels=>[:Rocket, :Secret], :dogs=>[:Scooby, :Scrappy, :DynoMutt]}
Run Code Online (Sandbox Code Playgroud)

我看到有人在另一个问题上发布这些内容,但我不明白为什么动物在第一种情况下显得空白.如果我输入

animals[:dogs]
Run Code Online (Sandbox Code Playgroud)

我得到了合适的数组.

ruby hash autovivification

4
推荐指数
1
解决办法
579
查看次数

标签 统计

ruby ×3

hash ×2

arrays ×1

autovivification ×1

hashtable ×1