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?
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
.
Look at Hash#default
:
=> h = { }
=> h.default = 0
=> h["a"]
#> 0
=> h["z"]
#> 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With