From: Logan Capaldo Date: 2005-12-20T01:04:56+09:00 Subject: Re: TheYAML change the id of Object On Dec 19, 2005, at 10:47 AM, Ross Bamford wrote: > On Mon, 19 Dec 2005 15:21:22 -0000, Logan Capaldo > wrote: > >> >> On Dec 19, 2005, at 9:10 AM, Andrea wrote: >> >>> I'm using an hash object and i use a Termine Object for the key >>> and, for >>> now, a String for the value. >>> >> >> You need to overload the == operator and the hash method. >> >> class Termine >> alias eql? == >> def ==(other) >> descrizione == other.descrizione and lingua == other. >> lingua >> end >> def hash >> (descrizione + lingua).hash >> end >> end >> >> t = Termine.new("Hi") >> t2 = Termine.new("Hi") >> >> t == t2 #=> true >> >> h = {} >> h[t] = "short hello" >> h #=> {#=>"short >> hello"} >> h.has_key?(t2) #=> true >> > > I was playing around with this, and now I'm doubly worried I have a > bug, or have missed something else. The last line in your code > gives out 'false' for me. I was experimenting with this: > > class Dclz > @str = "A string" > attr_reader :str > > def ==(o) > self.str == o.str > end > > def ===(o) > self.str === o.str > end > > def hash > self.str.hash > end > end > > case Dclz.new > when Dclz.new > puts "Works" > else > puts "doesn't" > end # => "Works" > > h = Hash.new { "Failure" } > h[d = Dclz.new] = "Expected" > > puts Dclz.new == Dclz.new # => true > puts Dclz.new.hash == Dclz.new.hash # => true > > puts h[d] # => "Expected" > puts h[Dclz.new] # => "Failure" > huh????!!!! > > And I cannot understand what's happening here. Someone, please > confirm that I'm either sane or stupid? > > (Tried on both ruby 1.8.3 (2005-09-21) [i386-linux] and ruby 1.9.0 > (2005-12-16) [i686-linux]) > > -- > Ross Bamford - rosco@roscopeco.remove.co.uk > As ts already mentioned, you missed the eql? part. Me aliasing it to == and implementing == instead is a function of my C++ (as opposed to lisp or smalltalk(?) ) upbringing.