Skip to content

Instantly share code, notes, and snippets.

@whylom
Created October 24, 2014 22:18
Show Gist options
  • Save whylom/c033b8b5c077d3d352ba to your computer and use it in GitHub Desktop.
Save whylom/c033b8b5c077d3d352ba to your computer and use it in GitHub Desktop.
Count instances of each member of an array
# 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