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
38 changes: 38 additions & 0 deletions word_counter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
def word_counter(filepath)
Copy link

Choose a reason for hiding this comment

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

word_counter would be a good name for a class. The best names for methods are either nouns representing the result, or verbs representing the action taken.

text = file_to_string(filepath)
words_arr = text.split(' ')
word_count = {}

words_arr.each do |word|
stripped_word = word.downcase.gsub(/[^a-z]/i, '')
if word_count.key? word
word_count[stripped_word] += 1
else
word_count[stripped_word] = 1 if stripped_word != ''
end
end

print_hash(word_count)
end

def file_to_string(filepath)
text = ''
file_obj = File.new(filepath, 'r')

while line = file_obj.gets
text += line
end
file_obj.close

Copy link

Choose a reason for hiding this comment

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

This will work, but check out File.read

text
end

def print_hash(hash)
hash = hash.sort_by { |_k, v| v }.reverse
Copy link

Choose a reason for hiding this comment

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

♨️


hash.each do |key, value|
puts "#{key} - #{value}"
end
end

word_counter('speech.txt')