From: Stefano Crocco Date: 2007-10-29T17:53:05+09:00 Subject: Re: uniq on custom objects 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)] > > => [#, # @name="apa">, #] > > a.uniq > > => [#, # @name="apa">, #] > > 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 => [#, #] I hope this helps Stefano