Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Bob Showalter

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Identify duplicates in an array

Method to return items that appear more than once in an array (or Enumerable)

   1  
   2  module Enumerable
   3    def dups
   4      inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
   5    end
   6  end


How it works: the inject method builds up a hash with keys for the unique values in the array and
a value representing the number of times the entry is found in the array. Any entries with a
value of 1 (i.e. not duplicated) are removed, and the resulting keys represents the duplicated
entries in the original array.

Example:

   1  
   2  arr = %w{foo bar baz bar baz qux foo zub}
   3  puts arr.dups.inspect
   4  # => ["baz", "foo", "bar"]

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS