Forum: Ruby Re: Making Array#uniq work

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
87e9a89c53ccf984db792113471c2171?d=identicon&s=25 Kroeger, Simon (ext) (Guest)
on 2006-01-24 13:04
(Received via mailing list)
> the one I
> would wish for. Any pointers? I'm running 1.8.2


Hi,

you have to define a 'hash' method because Array uses a Hash to remove
the duplicates.

e.g.:
----------------------------------------------------------
class A
   attr_accessor :a,:b
   def initialize a
     @a=a
     @b=Array.new
   end
   def << item
     @b<<item
   end

   def eql? other
     return true if @a==other.a && @b==other.b
   end

   def == other
     return eql?(other)
   end

   def hash
    a.hash * b.hash
   end
end


o1=A.new("a")
o2=A.new("a")
o1<<"o"
o2<<"o"
puts o1==o2
puts o1.eql?(o2)
p [o1,o2].uniq
----------------------------------------------------------

cheers

Simon
This topic is locked and can not be replied to.