2007/10/29, daniel =E5kerud <daniel.akerud / gmail.com>:
> 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 th=
ere
> something else I have to override?

You can make your life much easier by using Struct:

Obj =3D Struct.new :name do
  attr_accessor :number
  def initialize(name, number)
    self.name =3D name
    self.number =3D number
  end
end

irb(main):008:0> a =3D [Obj.new("apa", 1), Obj.new("apa", 2), Obj.new("smis=
k", 3)]
=3D> [#<struct Obj name=3D"apa">, #<struct Obj name=3D"apa">, #<struct Obj
name=3D"smisk">]
irb(main):009:0> a.uniq
=3D> [#<struct Obj name=3D"apa">, #<struct Obj name=3D"smisk">]

Kind regards

robert