Skip to content
Open
Changes from 2 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
29 changes: 29 additions & 0 deletions solution.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
TEXT = File.read('speech.txt')

def find_words text
words_regex = /\w+[a-z']*\w+/
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 this would make a little more sense defined as a constant outside the method.

Copy link
Member

Choose a reason for hiding this comment

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

It'd probably be a good idea to encapsulate these methods in a class as well, no?

text.downcase.scan words_regex
end

def count_words words_array
Hash.new(0).tap do |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.

Nice use of .tap

words_array.each { |word| word_count[word] += 1 }
end
end

def sort_words words_frequency_hash
words_frequency_hash.sort_by { |word, count| -count }
Copy link
Member

Choose a reason for hiding this comment

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

👍 Don't think I've seen anyone implement it this way before. I was putz'ing around with irb and {}.sort_by(&:last).reverse will do the same too.

end

def wordcount_print_format word
"#{word[1]} - #{word[0].capitalize}"
end

def print_sorted_word_counts sorted_words
sorted_words.each { |word| puts wordcount_print_format(word) }
end

words = find_words TEXT
word_freqs = count_words words
sorted_words = sort_words word_freqs
print_sorted_word_counts sorted_words