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)

module Enumerable
  def dups
    inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
  end
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:

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

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