Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

0 views
Skip to first unread message

andrea

unread,
May 11, 2008, 6:09:20 PM5/11/08
to
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.altervista.org

Marcin Mielżyński

unread,
May 11, 2008, 6:53:52 PM5/11/08
to
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

andrea

unread,
May 12, 2008, 4:30:25 AM5/12/08
to
Marcin Miel?y?ski <lo...@gazeta.pl> wrote:


> you also need to define #hash method:

Thank you !

Andrea


--

http://myretrocomputing.altervista.org

0 new messages