Reputation: 48916
I came across this Ruby
script:
frequency = Hash.new(0)
...
...
file.read.downcase.scan(/\b[a-z]{4,20}\b/){|word| frequency[word] =
frequency[word]+1}
The point I couldn't understand is frequency[word] = frequency[word]+1
Wouldn't frequency[word]
give me the word matched? How can we add it to 1
?
Upvotes: 1
Views: 50
Reputation: 13532
frequency
is defined as a hash with 0
as default value. So when frequency[word]
is invoked for the word
that wasn't recorded before it returns 0.
The code seems to count the different words in the text.
When it finishes, the frequency
will contain words as keys and number of times the particular word appears in the sentence as values.
You can play with it here: http://rubyfiddle.com/riddles/519da
Upvotes: 6