diff --git a/lib/readfile.rb b/lib/readfile.rb new file mode 100644 index 0000000..35dc760 --- /dev/null +++ b/lib/readfile.rb @@ -0,0 +1,31 @@ + +def readFile(file) + return File.read(file) +end + + +def getWords(text) + text.gsub!(/[^A-Za-z ]/,'') + data = Hash.new + temparray = text.to_s.split(" ").map(&:to_s) + for word in temparray + if(data.has_key?(word)) + data[word] += 1 + else + data[word] = 1 + end + end + return data +end + +def printWords(data) + data = data.sort_by { |key, value| value }.reverse + data.each do |key, value| + puts key.to_s + ' ' + value.to_s + end +end + + +text = readFile("/Users/apetit/CountingWords/speech.txt") +data = getWords(text) +printWords(data) diff --git a/spec/readfile_spec.rb b/spec/readfile_spec.rb new file mode 100644 index 0000000..b7f7c3b --- /dev/null +++ b/spec/readfile_spec.rb @@ -0,0 +1,24 @@ +require 'rspec' +require_relative '../lib/readfile.rb' + +describe 'Number of words' do + it 'get words return the proper number' do + expect(getWords("one two three four").count).to eq 4 + end +end + +describe 'Accounts for duplicates' do + it 'same word only gets counted once' do + expect(getWords("one two three one")["one"]).to eq 2 + expect(getWords("one two three one").count).to eq 3 + end +end + +describe 'No Special Chars' do + it 'No Special Chars' do + expect(getWords("one two! one")["two"]).to eq 1 + expect(getWords("one two. one")["two"]).to eq 1 + expect(getWords("one two- one")["two"]).to eq 1 + expect(getWords("one two? one")["two"]).to eq 1 + end +end