Created
October 24, 2014 22:18
-
-
Save whylom/c033b8b5c077d3d352ba to your computer and use it in GitHub Desktop.
Count instances of each member of an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# given an array | |
words = %w(duck duck goose cry baby cry) | |
# generate a hash that counts occurrences of each word, eg: | |
# {"duck"=>2, "goose"=>1, "cry"=>2, "baby"=>1} | |
# Method #1 | |
counts = Hash.new(0) | |
words.each { |word| counts[word] += 1 } | |
# Method #2 | |
counts = words.uniq.inject({}) do |counts, word| | |
counts.merge(word => words.count(word)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment