使用空数组意外行为初始化哈希

Initializing a Hash with empty array unexpected behaviour

我想用一个空 Array 初始化一个 Hash 并且对于每个新键将特定值推送到该数组。

这是我尝试做的事情:

a = Hash.new([])
# => {} 
a[1] << "asd"
# => ["asd"]
a
# => {}

a 的预期输出是 {1 => ["asd"]},但这并没有发生。我在这里错过了什么?

Ruby 版本:

ruby 2.0.0p598 (2014-11-13 revision 48408) [x86_64-linux]

随心所欲

a = Hash.new { |h, k| h[k] = [] }
a[1] << "asd"
a # => {1=>["asd"]}

阅读 Hash::new 文档中的以下几行。它真正解释了为什么你没有得到想要的结果。

new(obj) → new_hash

If obj is specified, this single object will be used for all default values.

新{|哈希,键|块}→new_hash

If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block’s responsibility to store the value in the hash if required.

您可以手动测试:

a = Hash.new([])
a[1].object_id # => 2160424560
a[2].object_id # => 2160424560

现在使用上述 Hash 对象创建样式,您可以看到每次访问 未知键 ,返回相同的 default对象。现在换句话说,我的意思是 block way :

b = Hash.new { |h, k| [] }
b[2].object_id # => 2168989980
b[1].object_id # => 2168933180

因此,使用 block 形式,每个 unknown key 访问,返回一个新的 Array 对象。