From: Logan Capaldo Date: 2005-12-20T00:21:22+09:00 Subject: Re: TheYAML change the id of Object 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. > The class Termine is this: > > class Termine > DEFAULT_LANG = "it" > attr_accessor :descrizione > attr_accessor :lingua > def initialize(descrizione="", lingua=DEFAULT_LANG) > @descrizione = descrizione > @lingua = lingua > end > end > > In my test file all is good (compare, edit, delete and reference), but > if I dump all in a file YAML and then I load the file YAML the equal > assertion have a failure. > The attributes 'descrizione' and 'lingua' on the key are the same, but > the problem is that the id of the object is changed... and so there is > the failure. > > test_yaml: before hash dump > #:Key T4 in lingua it -- Value: Definizione uno > #:Key T3 in lingua it -- Value: Definizione tre > #:Key T2 in lingua it -- Value: Definizione due > #:Key T1 in lingua it -- Value: Definizione uno > > test_yaml: after dump (is clear) > > test_yaml: after load > #:Key T4 in lingua it -- Value: Definizione uno > #:Key T3 in lingua it -- Value: Definizione tre > #:Key T2 in lingua it -- Value: Definizione due > #:Key T1 in lingua it -- Value: Definizione uno > > How can I solve this problem? > > Thanks to all for the help... > --Andrea. > > -- > Posted via http://www.ruby-forum.com/. > 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