Skip to content
Open
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions CountingWords.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
freq = Hash.new(0)
Copy link
Member

Choose a reason for hiding this comment

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

This is something that I learned later on that you can initialize a hash with default values. Kind of cool. Well done.

Anytime you build up an empty collection, iteratively build it up then utilize it as input for something else, you should always consider .reduce or a similar method as possibly a solution. in this case you're using .scan but reduce would have worked as well as .each_with_object.

http://batsov.com/articles/2013/12/04/using-rubys-each-with-object/

Choose a reason for hiding this comment

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

Hash with default values 😮 😮

file = File.open("speech.txt")
file.read.downcase.scan(/\b[a-z]{3,16}\b/){|word| freq[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.

how would you rewrite this to handle punctuation?

your script also doesn't handle words less than 3 characters? how would you rewrite this to take those into account?

Copy link
Member

Choose a reason for hiding this comment

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

This is the first time I think I've seen someone use .scan. me likes it but keep in mind the issues i stated in the other comment. 👍

freq = freq.sort_by{|a, b| b}
freq.reverse!
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 use .reverse here?

Copy link
Author

Choose a reason for hiding this comment

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

.reverse made the counters go from 1 to 33. .reverse! allowed it to go from 33 to 1.

freq.each{|word, freq| puts freq.to_s + " - " + word}