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/
Written by Catalin Ilinca
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#