Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@siruguri 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