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


class WordCounter
@@WORDS_REGEX = /\w+[a-z']*/
Copy link
Member

Choose a reason for hiding this comment

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

Class instance variables are generally frowned upon. https://github.com/bbatsov/ruby-style-guide#no-class-vars

This should work fine as a constant instead. (Drop the "@@".)

Copy link
Author

Choose a reason for hiding this comment

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

Wow, had no idea that a child's class variable OVERWRITES a class variable of the same name within its superclass. That's pretty surprising and now I see why class vars are not favored


def self.solve text
words = find_words TEXT
word_freqs = count_words words
sorted_words = sort_words word_freqs
print_sorted_word_counts sorted_words
end

def self.find_words text
text.downcase.scan @@WORDS_REGEX
end

def self.count_words words_array
Hash.new(0).tap do |word_count|
words_array.each { |word| word_count[word] += 1 }
end
end

def self.sort_words words_frequency_hash
words_frequency_hash.sort_by { |word, count| -count }
end

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

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


WordCounter.solve(TEXT)