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

Identify duplicates in an array (See related posts)

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"]


You need to create an account or log in to post comments to this site.


Click here to browse all 4852 code snippets

Related Posts