From: Yuri Leikind Date: 2001-09-16T01:18:36+09:00 Subject: [ruby-talk:21211] Re: using my own objects as hash keys - a question Lyle Johnson wrote: > > > Could someone explain to me why the following > > does not work as I expect: > > > > > > hash=Hash.new > > > > hash[key1]=6 > > > > puts hash[key1] #=> 6 > > # Ok, as expected > > > > puts hash[key2] #=> nil > > # Why?!! If key1.hash == key2.hash, why doesn't it work? > > > > # Same question here > > puts hash.has_key?(key1) #=> true > > puts hash.has_key?(key2) #=> false > > > > > > Have I missed something ? > > Well, yes, I guess you've missed how hash tables work. A hash table is > usually described as a collection of "buckets", one for each hash value. > Whenever you add a new key to a hash table, the code will compute the hash > value for that key, find the corresponding bucket for that hash value, and > place a reference to the key in that bucket. When you look up that key in > the hash table (e.g. by calling has_key?) the code once again computes the > hash code for the key, looks in the corresponding bucket -- which may now > have several different keys, all with the same hash value -- and looks for > the requested key. > > So even though key1 and key2 have the same hash code (6), you've only put > key1 in the hash table, and it's still a different instance than key2. If > you were to also add key2 to the hash table, they would both end up in the > same "bucket" and the hash table would include both keys. I got it. Thank you. Yuri Leikind