From: Clemens Hintze Date: 2002-03-28T01:49:34+09:00 Subject: Re: Hash.new(Hash.new) doesn't use Hash.new as default value In "Jonas Delfs" writes: > Hi - Hi too, > In the documentation for the 'new' method in the Hash class in Programming > Ruby it says that 'anObject' will be used as default value, but consider the > following example: > var = Hash.new(Hash.new) The documentation is true. It says that *anObject*, i.e. the reference to an (better *one* here) object is used as default value! So a new Hash will be created. That *one* instance will be passed to Hash::new as default value to be used, if a certain key does not exist. > var['index1'] = 'value1' > var['index2']['index22'] = 'value22' Because 'index2' does not exist, the instance serving as default value will be returned. *That* instance will get sent the []= message and therefore insert a association between key 'index22' and 'value22'. The default Hash instance contains now { 'index22' => 'value22' } > var['index3']['index32'] = 'value32' And here happens the same again. So after this line the Hash instance used as default value contain now: { 'index22' => 'value22', 'index32' => 'value32' } > var['index4'] = 'value4' > p var['donotexist'] > Why does "p var['donotexist']" output {"index32" => "value32", "index22" => > "value22"} - and _not_ just {} (a new Hash)? You have passed a default *value* to Hash::new above. That value happens to be the reference to a new created Hash instance. The reference of this one Hash instance is returned every time you try to access a key that does not exist. Look this: puts( var['index3'].id == var['donotexist'].id ) you see? Every time the *same* Hash instance is returned to you if you try to access a key that does not exist. In Ruby 1.7.x it is possible to do this: var = Hash.new { Hash.new } Now every time a key was not found, the block will be executed returning a brand new Hash instance. > If it's no bug, I think it's a bug in documentation. - and not a very logic > behavior. OTOH, I think it is a very logic and usefull behavior. Especially as we have now the block supporting Hash::new method :-) HTH, \cle -- Clemens Hintze mailto: c.hintze@gmx.net