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
Output: dogs3dog2
Code 1 class String 2 def word_count 3 frequencies = Hash.new(0) 4 downcase.scan(/(\w+([-'.]\w+)*)/) { |word, ignore| frequencies[word] += 1 } 5 return frequencies 6 end 7 end 8 9 puts %{Dogs dogs dog dog dogs.}.word_count10 puts %{ "That F.B.I. fella--he's quite the man-about-town."}.word_count
Output: dogs3dog2
quite1f.b.i1the1fella1that1man-about-town1he's1