You can always use a simple counter hash:
def duplicate_count(array)
array.each_with_object(Hash.new(0)) do |value, hash|
# Keep a count of all the unique values encountered
hash[value] += 1
end.count do |(value,count)|
# Compute how many have a count > 1
count > 1
end
end
duplicate_count([1,2,3,4])
# => 0
duplicate_count([1,2,2,3,4,4,2])
# => 2
If you'd prefer to return the duplicated values:
def duplicate_count(array)
array.each_with_object(Hash.new(0)) do |value, hash|
# Keep a count of all the unique values encountered
hash[value] += 1
end.each_with_object([ ]) do |(value,count), result|
# Collect those with count > 1 into a result array.
if (count > 1)
result << value
end
end
end