Recipe 1.9. Processing a String One Word at a Time
1 class String
2 def word_count
3 frequencies = Hash.new(0)
4 downcase.scan(/\w+/) { |word| frequencies[word] += 1 }
5 return frequencies
6 end
7 end
8
9 puts %{Dogs dogs dog dog dogs.}.word_count
2 def word_count
3 frequencies = Hash.new(0)
4 downcase.scan(/\w+/) { |word| frequencies[word] += 1 }
5 return frequencies
6 end
7 end
8
9 puts %{Dogs dogs dog dog dogs.}.word_count
Output: dogs3dog2
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Output: dogs3dog2
quite1f.b.i1the1fella1that1man-about-town1he's1