Skip to content
Open
Show file tree
Hide file tree
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
Binary file added .DS_Store
Binary file not shown.
38 changes: 38 additions & 0 deletions lib/wordcount.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
def shred line #split lines into words
line.split /[\?\.,_:;@#\n\$\^\*\<\>\%\&!{}\+\n\\"\)\(\-— ]+/
#personalize regex for 'word' definition
end

def add_to_list array_of_words, list #adds only new words to hash list
array_of_words.each do |word|
key = word.upcase.capitalize #downcase to prevent case mattering
if list.has_key? key #if word already exists, inc count
list["#{key}"]=list["#{key}"]+1
Copy link
Member

Choose a reason for hiding this comment

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

Since key is a string, there's no need to interpolate it into a new string. "#{key}" is better written as key.

When you want to increment a value in Ruby, the typical syntax is: foo += 1.

Together: list[key] += 1

else #else create new hash key and value
list["#{key}"] = 1
end
end
end

#reads file in and returns array for printing
def generate_list filename
input = File.new filename, "r+" #opens file for reading
list = Hash.new #creates hash for wordcount list
Copy link
Member

Choose a reason for hiding this comment

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

You can instantiate Hashes with a default value that is used when a key is not found. Use Hash.new(0) here and you won't need to check if a given key is already in the hash when you need to increment its value.

shredded = Array.new #temporary storage for lines
input.each_line do |line|
shredded = shred line #break lines into words
add_to_list shredded, list #adds words to hash of word, value pairs
end
array=list.to_a
array.sort!{|a,b| b[1]<=>a[1]} #sort by count
end

def print_list filename
list = generate_list filename
puts "#{list.count} words in list"
list.each do |pair| #prints
puts "#{pair[1]} — #{pair[0]}"
end
end

print_list "speech.txt"