考虑以下代码:
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代码:
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个哈希的元素?
哈希初始值设定项:
# 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)
我得到了合适的数组.