Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions countWords.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
file = File.open("speech.txt", "r")
content = file.read
frequency = Hash.new(0)
wordcount = content.split(" ")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think wordcount might not be the best name for this variable. What is actually being returned here is a list of short strings containing words and punctuation.

wordcount.each do |w|
w.gsub!(/\W|_/,"")
frequency[w] += 1
end
frequency = frequency.sort_by {|word,count| count}.reverse
frequency.each do |key,value|
puts "#{key}:#{value}"
end
file.close

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a pretty good procedural approach that is fine for solving this problem. However, just for fun (and because we have attributes and methods that act on those attributes), how about encapsulating this in a nice WordCounter class that accepts a filepath on initialization and can be asked to print out a word count? 😃

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this work for words containing a single apostrophe? E.g.: it's, another's, that's