From: Robert Klemme Date: 2004-06-18T16:33:22+09:00 Subject: Re: How to make generic #== method? "Zakaria" schrieb im Newsbeitrag news:20040617211611.GA4734@zakbox.local... > Hi, > > Currently I got many simple class which is just a simple record-like. > An example > ----------------------------------- > class LoopTag # :nodoc: > attr_reader :param > attr_reader :contents > > def initialize(param) > @param, @contents = param, [] > end > > def ==(other) > return false unless other.class == self.class > return other.param == @param && other.contents == @contents > end > end > ------------------------------------ > and I got a couple more class like this. > > Is there a way to make a generic #== or some Module that I can include ? > > I surely need it to do assert_equal on unit test. > You know, I just waste a couple hour tracking bug that doesn't exists > because I forgot to implement #== :) module MemberEquivalence def ==(o) instance_variables.each do |var| return false unless instance_variable_get(var) == o.instance_variable_get(var) end true end def hash h = 0 instance_variables.each do |var| val = instance_variable_get(var) h ^= val.hash unless val.nil? end h end alias :eql? :== end class Foo include MemberEquivalence attr_accessor :foo, :bar end >> f=Foo.new => # >> g=Foo.new => # >> f == g => true >> f.foo = "x" => "x" >> f == g => false >> f.foo = nil => nil >> f == g => true >> f.hash => 0 >> g.hash => 0 >> f.eql? g => true >> h={ f => 1 } => {#=>1} >> h[g] => 1 Regards robert