Skip to content

Instantly share code, notes, and snippets.

@siruguri
Created May 31, 2015 03:18
Show Gist options
  • Save siruguri/5502174cf9d61219e1b3 to your computer and use it in GitHub Desktop.
Save siruguri/5502174cf9d61219e1b3 to your computer and use it in GitHub Desktop.
Gathering counts of possibly duplicated items in an array
a = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4]
b = a.uniq
counts = b.inject({}) do |memo, key|
memo[key] = a.count(key)
memo
end
@siruguri
Copy link
Author

siruguri commented Oct 6, 2015

Another solution:

counts = a.group_by { |a| a}.map {|pair| {pair[0]=> pair[1].size}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment