为什么在使用默认对象初始化时我的哈希没有被填充

Why does my Hash not get filled when initializing with a default object

鉴于此代码:

h = Hash.new([])

3.times do |i|
  h[:a] << i
end

我希望 h{:a => [0, 1, 2]},但它是空的。我做错了什么?

正如 API 所说:

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

只要稍微重写一下代码,就会清楚发生了什么:

a = []
h = Hash.new(a)
3.times { |i| h[:a] << i }

# This is like:
# 3.times { |i| a << i }
# because `h` does not respond to your key :a

h
# => {} 
a
# => [0, 1, 2]

你想做的,是这样的:

h = Hash.new { |h, k| h[k] = [] }
3.times { |i| h[:a] << i }

h
# => {:a=>[0, 1, 2]}