1 Jun 2007, 1:55pm
/dev/ruby
by

2 comments

Using a hash to count incrementally

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:
  1. 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.