鉴于此代码:
h = Hash.new([])
3.times do |i|
h[:a] << i
end
我希望h
为{:a => [0, 1, 2]}
,但它是空的。我做错了什么?
答案 0 :(得分:7)
正如API所说:
如果指定了obj,则此单个对象将用于所有默认值 值。
通过对代码进行少量重写,应该清楚会发生什么:
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]}