Melissa Kaulfuss Melissa Kaulfuss - 3 months ago 10
Ruby Question

How to count non-unique values in a hash in Ruby

I'm trying to get a count of all the items

[:item_id]
with more than 1 occurance. This is what I have written – it's wrong I know. Hoping someone can point me in the right direction!

subscriptions = [
{user_id: 1, item_id: 3},
 {user_id: 3, item_id: 2},
 {user_id: 2, item_id: 3},
 {user_id: 6, item_id: 5},
 {user_id: 6, item_id: 2},
 {user_id: 1, item_id: 4}
]

unique_id = subscriptions_list.map {|id| id[:item_id]} > 1 }    
puts unique_id.count

Answer

You can use this:

subscriptions.each.with_object(Hash.new(0)) do |subscription, counts| 
    counts[subscription[:item_id]] += 1
end
# => {3=>2, 2=>2, 5=>1, 4=>1}
  • each will iterate over each element of subscription,
  • with_object is used to give an arbitrary object during an iteration, and return it,
  • Hash.new(0) creates a new hash with a default value of 0. This value is returned when accessing keys that do not exist in the hash
  • counts[subscription[:item_id]] += 1 will increment the value in the hash by one for the key subscription[:item_id]

And there you have counts by item_id.