Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing hash with default value and incrementing by 1

Tags:

ruby

hash

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?

like image 791
shivam Avatar asked Dec 04 '14 08:12

shivam


2 Answers

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.

like image 187
Yu Hao Avatar answered Sep 17 '22 15:09

Yu Hao


Look at Hash#default:

=> h = { }
=> h.default = 0
=> h["a"]
#> 0     
=> h["z"]
#> 0
like image 36
Philidor Avatar answered Sep 21 '22 15:09

Philidor