Hash of arrays - strange behavior

Hello,

Could somebody explain me the following behavior?

irb(main):001:0> h = Hash.new([])
=> {}
irb(main):002:0> h[1].push(1)
=> [1]
irb(main):003:0> h
=> {}
irb(main):004:0> h[1].push(1)
=> [1, 1]
irb(main):005:0> h
=> {}
irb(main):006:0> h[1].push(1)
=> [1, 1, 1]
irb(main):007:0> h[1]
=> [1, 1, 1]

I can’t get values using ‘each’ method for example.

TIA.

Jakub Kuźma wrote:

Hello,

Could somebody explain me the following behavior?

irb(main):001:0> h = Hash.new([])
=> {}
irb(main):002:0> h[1].push(1)
=> [1]
irb(main):003:0> h
=> {}

Hash.new(arg) makes arg the default, but it doesn’t assign to the hash.
You
want h = Hash.new {|h,k| h[k] = []}

HTH,
Sebastian

Dnia Wed, 3 Oct 2007 19:15:35 +0900
Sebastian H. [email protected] wrote:

Hash.new(arg) makes arg the default, but it doesn’t assign to the
hash. You want h = Hash.new {|h,k| h[k] = []}

HTH,

Thank you very much :-).