Initializing hash with default value and incrementing by 1

hash, ruby

Solution

I think all you need is to give the hash a default value of `0`

hash = Hash.new(0)

then for every occurrence of the key, you don't need to check its value, just increment it directly:

hash[key]+=1

Reference: `Hash#new`.

Problem

I need a hash whose keys should have default value 0. (basically I'm making a counter). Keys are not known so I cannot initialize them in beginning. Also with every occurrence of the key, the value should increase by 1. I have come up with this: ``` hash = {} hash[key] ? hash[key]+=1 : hash[key]=0 ``` This looks OK and short, but I don't like repeating `hash[key]` so many times in one line of code. Is there a better way to write this?

Original source