Lobosque Lucas wrote:
Is there a way to compare two objects without take its ID in
consideration? For example:
#<Game_Esper:0xdcc7e0 @str=6, @mdfel = 0, @name = "Ifrit"> ==
#<Game_Esper:0xeda51e @str=6, @mdfel = 0, @name = "Ifrit">
It'll return false, because the object ID is different. But i want it to
return true, because the arguments (is it the right name?) are all
equal.
This is one pattern I use, and (because it defines #eql? and #hash) it also gives you the hashing behavior you will probably want to go with it:
module ContentEquality
def hash
content.hash
end
def eql?(other)
other.class == self.class and content.eql? other.content
end
def ==(other)
other.class == self.class and content == other.content
end
end
class Game
include ContentEquality
def initialize str, mdfel, name
@str, @mdfel, @name = str, mdfel, name
end
def content
[@str, @mdfel, @name]
end
end
g1 = Game.new "foo", "bar", "baz"
g2 = Game.new "foo", "bar", "baz"
p g1 == g2 # ==> true
h = {}
h[g1] = true
p h[g2] # ==> true
···
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407