Skip to content

Conversation

@victoria-hall1998
Copy link

@victoria-hall1998 victoria-hall1998 commented Jun 27, 2017

CountingWords.rb Outdated
@@ -0,0 +1,6 @@
freq = Hash.new(0)
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?

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

CountingWords.rb Outdated
@@ -0,0 +1,6 @@
freq = Hash.new(0)
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.

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. 👍

@@ -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 😮 😮

@jaybobo
Copy link
Member

jaybobo commented Jun 28, 2017

Looks good. I'd also recommend encapsulating your stuff inside of a function or class. it's good practice when starting out.

https://sourcemaking.com/refactoring/extract-method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants