Using a hash to count incrementally
By chris on June 1st 2007 in /dev/ruby | 840 views
A hash is great for keeping track of counts of things if you we already know what those things are, but how to add a new thing without a bunch of cumbersome code? Use fetch():
RUBY:
-
count[item] = count.fetch(item, 0) + 1
If item already exists then it will add 1 to it. If item doesn't exist, it'll initialize it with a value of 0 and then add 1 to it.

sam responded on 01 Jun 2007 at 10:37 pm #
hash also has constructors that allow you to set the default value for non-existent hash items
irb(main):001:0> h = Hash.new(0)
=> {}
irb(main):002:0> h["this"] += 1
=> 1
irb(main):003:0> h["this"] += 1
=> 2
irb(main):004:0> h["this"]
=> 2
Chris responded on 02 Jun 2007 at 2:00 am #
Interesting. Cleaner and shorter, I like that.