Skip to content
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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
21 changes: 21 additions & 0 deletions word_count.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#Generates the count of each word in the file sorted by the maximum occured word first
def wordCount
Copy link
Member

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?

file = File.open("speech.txt")

words = file.read().downcase().split(/\W+/)
Copy link
Member

Choose a reason for hiding this comment

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

words_map = {}
Copy link
Member

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

words.map do |word|
if words_map.has_key?(word)
words_map[word] += 1
else
words_map[word] = 1
Copy link
Member

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

end
end
#words_map.sort {|x,y| -(x[1]<=>y[1])} -- 16.7s
#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
Copy link
Member

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.

https://sourcemaking.com/refactoring/smells/long-method

end

wordCount