[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Array#uniq with Hash elements... can't remove duplicates

myemail

5/11/2008 10:09:00 PM

Hello,

I am having some trouble trying to remove duplicate data from an array
of hashes. I've read on the pickaxe book that Array#uniq detects
duplicates using the eql? method on the elements, but it doesn't seem to
work even if I monkeypatch the Hash class:

class Hash
def eql? other
self == other
end
end

a={:foo=>'bar'}
b={:foo=>'bar'}
array=[a,b]

a.eql? b
=> true
array.uniq
=> [{:foo=>"bar"}, {:foo=>"bar"}]

Of course, I'd like to get only [{:foo=>"bar}] as a result. Thanks in
advance for any help...

Andrea


--

http://myretrocomputing.alte...
2 Answers

Marcin Mielzynski

5/11/2008 10:54:00 PM

0

andrea pisze:
> Hello,
>
> I am having some trouble trying to remove duplicate data from an array
> of hashes. I've read on the pickaxe book that Array#uniq detects
> duplicates using the eql? method on the elements, but it doesn't seem to
> work even if I monkeypatch the Hash class:
>
> class Hash
> def eql? other
> self == other
> end
> end

you also need to define #hash method:

class Hash
def eql? other
self == other
end

def hash
h = 0
each_pair do |k, v|
h ^= k.hash
h *=137
h ^= v.hash
end
h
end
end


lopex

myemail

5/12/2008 8:30:00 AM

0

Marcin Miel?y?ski <lopx@gazeta.pl> wrote:


> you also need to define #hash method:

Thank you !

Andrea


--

http://myretrocomputing.alte...