/ruby/word-count/phrase.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Phrase

  def initialize(phrase)
    # Since phrase is fixed, just generate the word count once.
    count_words(phrase)
  end

  def count_words(phrase)
    @counter = Hash.new(0)

    # Lowercase, strip punctuation (except for apostrophes),
    phrase = phrase.downcase.gsub(/[^\w']+/, ' ')

    # Split on whitespace and commas.
    words = phrase.split(/[,\s]/)

    # Count.
    words.each do |w|
      @counter[w] += 1
    end
  end

  def word_count
    @counter
  end

end

Comments


You're not logged in right now. Please login via GitHub to comment