Ruby snippet : Remove duplicates in an array

module Enumerable

  def dups

    inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys



arr = %w{foo bar baz bar baz qux foo zub}

puts arr.dups.inspect # => ["baz", "foo", "bar"] 

8 comments so far

  1. Florian Groß on

    Heh, you just reimplemented Array#uniq. Which makes me wonder why this isn’t defined in Enumerable already. Hm. Nice code, though!

  2. Clifford Heath on

    Actually the snippet is misnamed. It *returns* an array of the items that are duplicated in the array. It isn’t a reimplementation of #uniq.

  3. sandip on

    a = [1,2,3,3,4,”A”,’A’,5]

    a = a.uniq =>[1,2,3,4,”A”,5]

    I think, it will help.

    • AK on

      u r awesome!!!

  4. Sb on

    No, sandip. That’s not what the above code does.

  5. Matt on

    Thank you for the useful code…just for the record…it is NOT the same as uniq!!!

  6. Mark Ellul (@mark_ellul) on

    This finds the dups, not creates an array of uniques. Great code

  7. Andy on

    How about:

    >> a = [1,1,2,3,3,4]
    => [1, 1, 2, 3, 3, 4]
    >>{|d| a.count(d) > 1 }.uniq
    => [1, 3]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: