Tendo esta matriz:
words = %w(how much wood would a wood chuck chuck)
Você pode contar ocorrências como:
counts = Hash.new 0
words.each do |word|
counts[word] += 1
end
# {"how"=>1, "much"=>1, "wood"=>2, "could"=>1, "a"=>1, "chuck"=>2}
Ou a versão de 1 linha:
words.each_with_object(Hash.new(0)) { |word,counts| counts[word] += 1 }
# {"how"=>1, "much"=>1, "wood"=>2, "could"=>1, "a"=>1, "chuck"=>2}
Fonte original: http://blog.jerodsanto.net/2013/10/ruby-quick-tip-easily-count-occurrences-of-array-elements/