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

Discussion in 'Ruby' started by andrea, May 11, 2008.

  1. andrea

    andrea Guest

    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
    andrea, May 11, 2008
    #1
    1. Advertising

  2. 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
    Marcin Mielżyński, May 11, 2008
    #2
    1. Advertising

  3. andrea

    andrea Guest

    andrea, May 12, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. rp
    Replies:
    1
    Views:
    494
    red floyd
    Nov 10, 2011
  2. Wolfgang Nádasi-Donner

    Array#uniq - Comparison doesn't use 'eql?' and 'hash'

    Wolfgang Nádasi-Donner, Feb 20, 2007, in forum: Ruby
    Replies:
    0
    Views:
    87
    Wolfgang Nádasi-Donner
    Feb 20, 2007
  3. Wolfgang Nádasi-Donner

    Array#uniq - Comparison doesn't use 'eql?' and 'hash'

    Wolfgang Nádasi-Donner, Feb 20, 2007, in forum: Ruby
    Replies:
    3
    Views:
    115
    Daniel Finnie
    Feb 20, 2007
  4. senthil
    Replies:
    10
    Views:
    389
  5. Martin Kissner

    randomly choose some uniq elements of an array

    Martin Kissner, Jan 19, 2006, in forum: Perl Misc
    Replies:
    18
    Views:
    187
    Anno Siegel
    Jan 23, 2006
Loading...

Share This Page