From: Steve Tuckner Date: 2001-04-18T00:09:11+09:00 Subject: [ruby-talk:13759] Odd Hash Behavior (long) 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" } ------------------------------- produces the following output ------------------------------- aTestHash['A'] = 1 aTestHash['B'] = 1 All Hash values: A = 1 ------------------------------- I have made this work by testing for key existence and adding the new entry manually like the following if !aTestHash.has_key?(index) then aTestHash[index] = A.new end aTestHash[index].add_one Why doesn't the method above work as expected (why no B in the hash?) and is there a consise way to do this that I don't know about. Thanks, Steve Tuckner