From: ts Date: 2001-09-16T01:18:38+09:00 Subject: [ruby-talk:21214] Re: using my own objects as hash keys - a question >>>>> "Y" == Yuri Leikind writes: Y> Have I missed something ? Yes, when you want to re-define #hash you must also redefine #eql? You have at http://www.ruby-lang.org/en/man-1.4/Object.html#hash Returns the integer hash value of the object. It is used in the Hash class to calculate the holding place of an object. The hash value of two objects must be equal, where these two objects are equal by using eql? operator. So, whenever you redefine the definition of the eql? operator in any class, don't forget to redefine hash method according to the definition. For example : pigeon% cat b.rb #!/usr/bin/ruby class MyObject attr_reader :someAttr def initialize (someAttr) @someAttr=someAttr end def eql? other other.kind_of?(self.class) && someAttr == other.someAttr end def hash @someAttr.hash end end key1=MyObject.new('qwerty') key2=MyObject.new('qwerty') puts key1.hash == key2.hash #=> true hash=Hash.new hash[key1]=6 puts hash[key1] #=> 6 puts hash[key2] #=> nil puts hash.has_key?(key1) #=> true puts hash.has_key?(key2) #=> false pigeon% pigeon% b.rb true 6 6 true true pigeon% -- Guy Decoux