Last Updated: February 25, 2016
·
8.779K
· opinel

Count duplicate elements in ruby array (Ruby 1.9+)

Returns a hash with the element value as a key and its count

a = [1, 2, 3, 2, 5, 6, 7, 5, 5]
a.each_with_object(Hash.new(0)) { |o, h| h[o] += 1 }

# => {1=>1, 2=>2, 3=>1, 5=>3, 6=>1, 7=>1}

In order to filter the result with a certain threshold, add ...

.map{|k,v| k if v >= 2}.compact

# => [2, 5]