ruby - Why does my Hash not get filled when initializing with a default object -
this question has answer here:
given code:
h = hash.new([]) 3.times |i| h[:a] << end
i expect h
{:a => [0, 1, 2]}
, empty. doing wrong?
as api says:
if obj specified, single object used default values.
with small rewrite of code, should become clear happens:
a = [] h = hash.new(a) 3.times { |i| h[:a] << } # like: # 3.times { |i| << } # because `h` not respond key :a h # => {} # => [0, 1, 2]
what want do, this:
h = hash.new { |h, k| h[k] = [] } 3.times { |i| h[:a] << } h # => {:a=>[0, 1, 2]}
Comments
Post a Comment