From: Ben Ben Date: 2009-12-26T05:58:37+09:00 Subject: Re: Making a counter for each word's occurrences in a string Ben Ben wrote: > By looking at this method below, I couldn't understand a few things. > Let me list the method first! > > 1) def count_frequency(word_list) > 2) counts = Hash.new(0) > 3) for word in word_list > 4) counts[word] += 1 > 5) end > 6) counts > 7) end > > p count_frequency(["sparky", "the", "cat", "sat", "on", "the", "mat"]) > > ---- > that code above produces {"sparky" => 1, "the" => 2, "cat"=>1, "on"=>1, > "mat"=>1} > > What I don't understand is that why line 6 is there. OK, like 4, it > seems counts[word] combines to pin point which word and add 1 to the > counter of that word, right? Because I'm confuse how ruby works as it's > so compact and nice, and under the hood I have no idea. So line 2 is to > create an empty hash with 0 item and deposits as counts (object)? Using > for loop to go through each word in word_list, adding 1 to counts[word], > but I thought counts[word] produces a position of a word and not a > counter. OK, you can say I'm completely confused about the whole code > above. > > Help? > > Thanks in advance. 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. -- Posted via http://www.ruby-forum.com/.