Melissa Kaulfuss Melissa Kaulfuss - 1 year ago 85
Ruby Question

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

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

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 = {|id| id[:item_id]} > 1 }    
puts unique_id.count

Answer Source

You can use this:

subscriptions.each.with_object( do |subscription, counts| 
    counts[subscription[:item_id]] += 1
# => {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,
  • 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download