diff --git a/count.rb b/count.rb new file mode 100644 index 0000000..a676e7d --- /dev/null +++ b/count.rb @@ -0,0 +1,40 @@ +class WordCount + attr_accessor :speech + attr_reader :counted_words + + def load_file(path) + @speech = File.read(path) + end + + def parse_words + @speech.gsub!(/[^0-9a-zA-Z\s]/, '') + @speech.gsub!(/\s+/, ' ') + @speech.downcase!.strip! + @speech = @speech.split(' ') + end + + def count_words + @counted_words = Hash.new + @speech.each do |word| + if @counted_words.include?(word) + @counted_words[word] += 1 + else + @counted_words[word] = 1 + end + end + end + + def report + sorted_words = @counted_words.sort_by { |word, count| -count } + sorted_words.each do |word, count| + puts count.to_s + ' - ' + word + end + end + + def run + load_file('speech.txt') + parse_words + count_words + report + end +end diff --git a/count_spec.rb b/count_spec.rb new file mode 100644 index 0000000..662edc1 --- /dev/null +++ b/count_spec.rb @@ -0,0 +1,26 @@ +require 'rspec' +require_relative 'count' + +describe 'WordCount' do + let(:words) { WordCount.new } + + it "returns text when file is loaded" do + expect(words.load_file('speech.txt')).not_to be_nil + end + + it "speech contains no special characters after parsing" do + words.load_file('speech.txt') + words.parse_words + expect(words.speech =~ /^0-9a-zA-z\s/i).to be nil + end + + it "counts words correctly" do + words.speech = "One two three one two four" + words.parse_words + words.count_words + expect(words.counted_words["one"]).to eq 2 + expect(words.counted_words["two"]).to eq 2 + expect(words.counted_words["three"]).to eq 1 + expect(words.counted_words["four"]).to eq 1 + end +end diff --git a/run.rb b/run.rb new file mode 100644 index 0000000..6f53611 --- /dev/null +++ b/run.rb @@ -0,0 +1,4 @@ +require_relative 'count' + +words = WordCount.new +words.run