From: Dave Thomas Date: 2002-09-10T07:44:12+09:00 Subject: Re: How best to histogram words? andrew_queisser@Hp.com (andrew queisser) writes: > I want to count the occurrence of specific words. In the past I've > used a hash as shown below. Is there a better way? I don't know which > words will occur, otherwise I'd just preinitialize the hash to all > zeros. > # option 1: try to increment cell, catch error > # option 2: initialize on first use # option 3: use Hash's default value :) counts = Hash.new(0) ARGF.each {|line| line.scan(/\w+/).each {|w| counts[w] += 1}} counts.keys.sort.each {|k| printf("%4d: %s\n", counts[k], k) } Cheers Dave