From: Phillip Gawlowski Date: 2009-12-26T06:39:17+09:00 Subject: Re: Making a counter for each word's occurrences in a string On 25.12.2009 21:58, Ben Ben wrote: > Also I forgot to add that how on earth ruby in the end knows to produce > sparky =>1, the =>2, cat =>1, etc... even though the code above doesn't > seem to be relate the counter with the word anywhere, and yet using p > command it knows to relate each word with its occurrence's counts. I modified your script a little: def count_frequency(word_list) counts = Hash.new(0) for word in word_list counts[word] += 1 end puts "counts' class: #{counts.class}" puts "inspect counts: #{counts.inspect}" puts "counts' Hash keys: #{counts.keys.join("; ")}" counts end p count_frequency(["sparky", "the", "cat", "sat", "on", "the", "mat"]) Output: c:\Scripts>ruby word_freq.rb counts' class: Hash inspect counts: {"mat"=>1, "cat"=>1, "sat"=>1, "the"=>2, "on"=>1, "sparky"=>1} counts' Hash keys: mat; cat; sat; the; on; sparky {"mat"=>1, "cat"=>1, "sat"=>1, "the"=>2, "on"=>1, "sparky"=>1} The mystery is solved in line 4: counts[word] += 1 which tells Ruby to use "word" as the name for the key. If the key doesn't exist, it is created, with the count of "1". Further ocurrences increment the count (obviously enough). -- Phillip Gawlowski Wishing everyone a merry Christmas, and happy holidays!