Alle luned=EC 29 ottobre 2007, daniel =E5kerud 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 =3D name
>     @number =3D number
>   end
>   def hash
>     return @name.hash
>   end
> end
>
> a =3D [Obj.new("apa", 1), Obj.new("apa", 2), Obj.new("smisk", 3)]
>
> =3D> [#<Obj:0x31baca8 @number=3D1, @name=3D"apa">, #<Obj:0x31bac80 @numbe=
r=3D2,
> @name=3D"apa">, #<Obj:0x31bac58 @number=3D3, @name=3D"smisk">]
>
> a.uniq
>
> =3D> [#<Obj:0x31baca8 @number=3D1, @name=3D"apa">, #<Obj:0x31bac80 @numbe=
r=3D2,
> @name=3D"apa">, #<Obj:0x31bac58 @number=3D3, @name=3D"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 o=
bjects have the same name:

class Obj
  ...
  def eql? other
    @name.eql? other.name
  end

end

a =3D [Obj.new("apa", 1), Obj.new("apa", 2), Obj.new("smisk", 3)]

p a.uniq

=3D> [#<Obj:0xb7b7f75c @name=3D"apa", @number=3D1>, #<Obj:0xb7b7f57c @name=
=3D"smisk", @number=3D3>]

I hope this helps

Stefano