Ruby idiom for updating or inserting a hash map

Is there a common ruby ​​idiom for this code:

if hashmap.has_key?(key)
    hashmap[key] += 1
else
    hashmap[key] = 1
end

      

It looks like there might be a higher order function here that helps here. I hope for something like

hashmap[key].insertOrUpdate { 1 }, {|value| value += 1}

      

Edit: While @ Santhosh's answer is cool and works with my specific example, I'm more interested in the general case. I think @sawa's answer gives the most flexibility as the code passed in is blocking complex logic like hash hash etc.

+3


source to share


4 answers


Instead of what you did, the better way is:

hashmap = Hash.new{|h, k| h[k] = 0}

      



Then you only need to do:

hashmap[key] += 1

      

0


source


You can use what nil.to_i

is0



hashmap[key] = hashmap[key].to_i + 1

      

+2


source


You can use fetch

to specify the default:

hashmap[key] = hashmap.fetch(key, 0) + 1

      

+2


source


You can write:

hashmap = {}
key = 'cat'
hashmap[key] = (hashmap[key] || 0) + 1 #=> 1
hashmap[key] = (hashmap[key] || 0) + 1 #=> 2

      

+1


source







All Articles