Last Updated: February 25, 2016
·
432
· ducknorris

Facebook Twitter Google Tumblr Ruby: Count Occurrences of Array Elements

Having this array:

words = %w(how much wood would a wood chuck chuck)

You can count occurences like so:

counts = Hash.new 0
words.each do |word|
  counts[word] += 1
end

# {"how"=>1, "much"=>1, "wood"=>2, "could"=>1, "a"=>1, "chuck"=>2}

Or the 1 line version:

words.each_with_object(Hash.new(0)) { |word,counts| counts[word] += 1 }

# {"how"=>1, "much"=>1, "wood"=>2, "could"=>1, "a"=>1, "chuck"=>2}

Original source: http://blog.jerodsanto.net/2013/10/ruby-quick-tip-easily-count-occurrences-of-array-elements/