B
Ben Ben
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.
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.