-
Notifications
You must be signed in to change notification settings - Fork 36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Word Count Solution(Shabbir Saifee) #47
base: master
Are you sure you want to change the base?
Word Count Solution(Shabbir Saifee) #47
Conversation
@@ -0,0 +1,21 @@ | |||
#Generates the count of each word in the file sorted by the maximum occured word first | |||
def wordCount |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why not a more object oriented solution?
def wordCount | ||
file = File.open("speech.txt") | ||
|
||
words = file.read().downcase().split(/\W+/) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
file = File.open("speech.txt") | ||
|
||
words = file.read().downcase().split(/\W+/) | ||
words_map = {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Anytime you instantiate an empty collection in order to iteratively build it up is a good clue that you should probably look to use a method like .map
or .reduce
if words_map.has_key?(word) | ||
words_map[word] += 1 | ||
else | ||
words_map[word] = 1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hash.new
lets you set default values.
https://ruby-doc.org/core-1.9.3/Hash.html
#words_map.sort {|x,y| y[1] <=> x[1]} -- 12.3s | ||
#words_map.sort_by {|k,v| -v} -- 5.9s | ||
#words_map.sort_by {|k,v| v}.reverse -- 3.7 | ||
puts words_map.sort_by {|k,v| v}.reverse.to_h |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Whether you go for a more functional or OOP approach; consider SRP in order to improve readability and maintability.
@jaybobo