From: Joel VanderWerf Date: 2002-09-10T07:44:01+09:00 Subject: Re: How best to histogram words? andrew queisser wrote: > 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. > > Thanks, Andrew > > foo = Hash.new > bar = Hash.new > while l = gets > l.split.each { |w| > # option 1: try to increment cell, catch error > begin > foo[w] += 1 > rescue NameError > foo[w] = 1 > end > > # option 2: initialize on first use > bar[w] = 0 if !bar[w] > bar[w] += 1 Two other approaches to opt 2: bar[w] ||= 0 bar[w] += 1 and bar[w] = bar[w].to_i + 1 > } > end > puts foo > puts bar