From: Josh Cheek Date: 2013-06-18T01:06:55+09:00 Subject: Re: Comparing objects --089e01182b3ee9aeb804df5bc825 Content-Type: text/plain; charset=ISO-8859-1 On Mon, Jun 17, 2013 at 10:52 AM, Thom T. wrote: > How do I compare two objects in Ruby, considering only attributes > values? > > For example: > > class Foo > attr_accessor :bar, :baz > end > > lorem = Foo.new > ipsum = Foo.new > > lorem.bar = 1 > lorem.baz = 2 > > ipsum.bar = 1 > ipsum.baz = 2 > > puts lorem == ipsum # false > > Both objects belongs to the same class and also have the same attributes > values. > > Thanks. > > I'd do it like this class Foo attr_accessor :bar, :baz def ==(foo) foo.kind_of?(self.class) && bar == foo.bar && baz == foo.baz end end Only define <=> if your foos are ordered. --089e01182b3ee9aeb804df5bc825 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable On Mon, Jun 17, 2013 at 10:52 AM, Thom T. <lists@ruby-forum.com>= wrote:
How do I compare two objects in Ruby, considering only attributes
values?

For example:

=A0 class Foo
=A0 =A0 =A0 attr_accessor :bar, :baz
=A0 end

=A0 lorem =3D Foo.new
=A0 ipsum =3D Foo.new

=A0 lorem.bar =3D 1
=A0 lorem.baz =3D 2

=A0 ipsum.bar =3D 1
=A0 ipsum.baz =3D 2

=A0 puts lorem =3D=3D ipsum # false

Both objects belongs to the same class and also have the same attributes values.

Thanks.


I'd do it like this
<= br>
class Foo
=A0 attr_accessor :bar, :baz
=A0 def =3D=3D(foo)
=A0 =A0 foo.kind_of?(self.class) && b= ar =3D=3D foo.bar && baz =3D=3D foo.baz
=A0 end
end

Only define <=3D> if your foos ar= e ordered.
--089e01182b3ee9aeb804df5bc825--