How do I increment a value for an uninitialized key in a hash?

hashtable, ruby

Solution

you can set default value of hash in constructor

h = Hash.new(0)
h[:ferrets] += 1
p h[:ferrets]

note that setting default value has some pitfalls, so you must use it with care.

h = Hash.new([]) # does not work as expected (after `x[:a].push(3)`, `x[:b]` would be `[3]`)
h = Hash.new{[]} # also does not work as expected (after `x[:a].push(3)`  `x[:a]` would be `[]` not `[3]`)
h = Hash.new{Array.new} # use this one instead

Therefore using `||=` might be simple in some situations

h = Hash.new
h[:ferrets] ||= 0
h[:ferrets] += 1

Problem

If I try to increment the value for a key that does not yet exist in a hash like so ``` h = Hash.new h[:ferrets] += 1 ``` I get the following error: ``` NoMethodError: undefined method `+' for nil:NilClass ``` This makes sense to me, and I know this must be an incredibly easy question, but I'm having trouble finding it on SO. How do I add and increment such keys if I don't even know in advance what keys I will have?

Original source