From: Robert Klemme Date: 2009-03-01T07:33:58+09:00 Subject: Re: Newbie question > Hash workings On 28.02.2009 22:15, AD60 wrote: > I am puzzled by the workings a the following program. I placed the > output after the corresponding lines. To me it lookes like a sort of > bug in the workings of de p method. Can anybody set me straight? p works correctly but... > h = Hash.new([]) > h[0] = [1,2,3] > p h #> {0=>[1, 2, 3]} > h[0] += [4] > p h #> {0=>[1, 2, 3, 4]} > h[1] += [10,11] > p h #> {0=>[1, 2, 3, 4], 1=>[10, 11]} > h[1] << 12 > p h #> {0=>[1, 2, 3, 4], 1=>[10, 11, 12]} > h[2] << 20 > p h #> {0=>[1, 2, 3, 4], 1=>[10, 11, > 12] ? > p h[2] #> > [20] ??? > h[2] << 21 > p h #> {0=>[1, 2, 3, 4], 1=>[10, 11, > 12]} ? > h[2] += [22] > p h #> {0=>[1, 2, 3, 4], 1=>[10, 11, 12], 2=>[20, > 21, 22]} ???????? ... you are modifying the default value of the Hash in those cases where you place the question marks. The default value is the one returned in case a key does not exist. But there is no automatic insertion, that's why you do not see key 2 after doing h[2] << 20. You probably rather want this famous idiom: h = Hash.new {|ha,ke| ha[ke] = []} Now run your tests again. :-) Kind regards robert