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
43 changes: 43 additions & 0 deletions lib/countwords.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class CountWords

attr_accessor :word_count
Copy link
Member

Choose a reason for hiding this comment

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

This word_count isn't used yet. You can probably delete all the @@s and then you would be using it.


def count_words_from_file(file)
count_file = File.open(file, "r")
count_file.each_line do |line|
next if line.empty?
@@word_count = Hash.new
Copy link
Member

Choose a reason for hiding this comment

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

It seems like we start with a fresh Hash on every line. Is that a bug?

word = line.split
word.each do |wrd|
next if wrd !~ /(\w+)/
wrd = wrd[/(\w+)/]
Copy link
Member

Choose a reason for hiding this comment

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

Splitting the line, iterating, and making sure each word matches \w+, can be simplified using String#scan.

if @@word_count.has_key?(wrd)
@@word_count[wrd] = @@word_count[wrd] + 1
else
@@word_count[wrd] = 1
end
end
display_word_count_asc
Copy link
Member

Choose a reason for hiding this comment

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

I think it would be better to not display while you build up the data. How about if the client code (outside this class) asks for the display something like:

word_counter = CountWords.new
word_counter.count_words_from_file("speech.txt")
word_counter.display_word_count_asc

end

count_file.close
@@word_count
end

def display_word_count_asc
puts ""
puts "'''''"
@@word_count.sort{|a,b| a[1]<=>b[1]}.each { |word|
Copy link
Member

Choose a reason for hiding this comment

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

Rubyists tend to use {} for single line block, and do/end for multiline blocks.

Check out Rubocop for automated checks for stuff like this. It enforces this style guide.

puts "#{word[1]} - #{word[0]}"
}
puts "'''''"
end

end

def count_data
data = CountWords.new
data.count_words_from_file("speech.txt")
end

count_data