-
Notifications
You must be signed in to change notification settings - Fork 36
Object oriented solution? #34
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
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| class TextParser | ||
| attr_reader :text, :word_counts | ||
| def initialize(file) | ||
| @text = IO.read(file) | ||
| @word_counts = {} | ||
| end | ||
|
|
||
| def remove_newlines | ||
| text.gsub(/\s+/, ' ').strip | ||
| end | ||
|
|
||
| def parsed_text | ||
| remove_newlines.split(" ").map do |string| | ||
| string.gsub(/[^a-zA-Z0-9'-]/i, '').downcase | ||
| end | ||
| end | ||
|
|
||
| def count_words | ||
| parsed_text.each do |word| | ||
| if word_counts.key?(word) | ||
| word_counts[word] += 1 | ||
| else | ||
| word_counts[word] = 1 | ||
| end | ||
| end | ||
| end | ||
|
|
||
| def sorted_counts | ||
| word_counts.sort_by {|_key, value| -value} | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I bet there are people that wouldn't think this is readable, but I love the simplicity of it. It would be a slight improvement to give There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. +1. Variables should have meaningful names. |
||
| end | ||
|
|
||
| def parse | ||
| count_words | ||
| sorted_counts.each do |pair| | ||
| puts "#{pair[1]} - #{pair[0]}" | ||
| end | ||
| end | ||
| end | ||
|
|
||
|
|
||
|
|
||
| p = TextParser.new("speech.txt") | ||
| p.parse | ||
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.
If you instantiate the
word_countshash with a default value of0, you wouldn't need to check if the word has already been seen.http://ruby-doc.org/core-2.2.2/Hash.html#method-c-new