From: David Alan Black Date: 2001-04-18T00:38:47+09:00 Subject: [ruby-talk:13761] Re: Odd Hash Behavior (long) Hello -- On Wed, 18 Apr 2001, Steve Tuckner wrote: > Could someone explain the following behavior? > > The following code > ------------------------------- > class A > attr_reader :value > def initialize > @value = 0 > end > def add_one > @value += 1 > end > end > > aTestHash = Hash.new(A.new) > > aTestHash['A'] = A.new > aTestHash['A'].add_one > aTestHash['B'].add_one > print "aTestHash['A'] = #{aTestHash['A'].value}\n" > print "aTestHash['B'] = #{aTestHash['B'].value}\n" > > print "\nAll Hash values:\n" > aTestHash.each { |aKey, aA| print "#{aKey} = #{aA.value}\n" } ... => > aTestHash['A'] = 1 > aTestHash['B'] = 1 > > All Hash values: > A = 1 Your hash will use the default value you give it in place of nil for non-existent keys -- but the keys are still non-existent :-) They don't get created automatically. Also note that when you do this: h = Hash.new(some_method) the method get called only once, and the return value of that call is used for all subsequent non-existent key fetches. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav