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…
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
Hashes of the objects must also match:
shot@devielle:~$ irb
class Hash
def hash
to_a.hash
end
alias eql? ==
?> end
=> nil
a = {:foo => ‘bar’}
=> {:foo=>“bar”}
b = {:foo => ‘bar’}
=> {:foo=>“bar”}
[a,b].uniq
=> [{:foo=>“bar”}]
That said, monkeypatching Hash in this way is a (very) bad idea.