From: Dave Howell Date: 2005-10-20T05:25:25+09:00 Subject: Re: How do you write an equality method? On Oct 17, 2005, at 16:24, David Corbin wrote: > Without getting into the details of which equality method (eql?, > equal?, ==), > I'm curious about how such a method should be written for class where > you're > trying to keep the interface appropriatley private. > > Consider: > > class Foo > def initialize(color) > @color = color > end > . > . > . > end > > If I do not wish to expose color via an attr_reader, how do I write an > equality method for this class? If Foo-class objects are the same if they have the same color . . . redOne = Foo.new(red) greenOne = Foo.new(green) pineOne = Foo.new(green) class Foo def ==(other) self.color == other.color end end Now, redOne == greenOne is false. greenOne == pineOne is true. I did something similar when trying to sort iTunes music tracks: def <=>(other) answer = self.artist <=> other.artist answer = self.album <=> other.album if answer == 0 answer = self.name <=> other.name if answer == 0 answer = self.dbid <=> other.dbid if answer == 0 return answer end