Given this code:
h = Hash.new([])
3.times do |i|
h[:a] << i
end
I expect h
to be {:a => [0, 1, 2]}
, but it is empty. What am I doing wrong?
Given this code:
h = Hash.new([])
3.times do |i|
h[:a] << i
end
I expect h
to be {:a => [0, 1, 2]}
, but it is empty. What am I doing wrong?
As the API says:
If obj is specified, this single object will be used for all default values.
With a small rewrite of your code, it should become clear what happens:
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]
What you want to do, is this:
h = Hash.new { |h, k| h[k] = [] }
3.times { |i| h[:a] << i }
h
# => {:a=>[0, 1, 2]}