Stefano Crocco
10/29/2007 8:53:00 AM
Alle lunedì 29 ottobre 2007, daniel åkerud ha scritto:
> I cannot get uniq to work with an array of custom class-objects. It seems
> overriding hash is now enough. This is what I mean:
>
> class Obj
> attr_reader :name, :number
> def initialize(name, number)
> @name = name
> @number = number
> end
> def hash
> return @name.hash
> end
> end
>
> a = [Obj.new("apa", 1), Obj.new("apa", 2), Obj.new("smisk", 3)]
>
> => [#<Obj:0x31baca8 @number=1, @name="apa">, #<Obj:0x31bac80 @number=2,
> @name="apa">, #<Obj:0x31bac58 @number=3, @name="smisk">]
>
> a.uniq
>
> => [#<Obj:0x31baca8 @number=1, @name="apa">, #<Obj:0x31bac80 @number=2,
> @name="apa">, #<Obj:0x31bac58 @number=3, @name="smisk">]
>
> But i want only one instance of "apa", and it doesn't matter which. Is
> there something else I have to override?
>
> /D
I think you also need to override eql? so that it returns true if the two objects have the same name:
class Obj
...
def eql? other
@name.eql? other.name
end
end
a = [Obj.new("apa", 1), Obj.new("apa", 2), Obj.new("smisk", 3)]
p a.uniq
=> [#<Obj:0xb7b7f75c @name="apa", @number=1>, #<Obj:0xb7b7f57c @name="smisk", @number=3>]
I hope this helps
Stefano