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?
David
Use a protected accessor:
class Foo
def initialize( color )
@color = color
end
attr_reader :color
protected :color
def ==( other )
@color == other.color
end
end
Or cheat:
class Foo
def initialize( color )
@color = color
end
def ==( other )
@color == other.instance_eval { @color }
end
end
Hope that helps.
James Edward Gray II
What would make two objects 'equal' ?
James
--
http://www.ruby-doc.org - The Ruby Documentation Site
http://www.rubyxml.com - News, Articles, and Listings for Ruby & XML
http://www.rubystuff.com - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com - Playing with Better Toys
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