Identify duplicates in an array
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"]