From 5d28c790f4fff6ddadaaa9472eda07d587de5171 Mon Sep 17 00:00:00 2001 From: maxdignan Date: Mon, 21 Dec 2015 08:52:47 -0500 Subject: [PATCH 1/2] completed challenge --- parser.rb | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 parser.rb diff --git a/parser.rb b/parser.rb new file mode 100644 index 0000000..64d1a42 --- /dev/null +++ b/parser.rb @@ -0,0 +1,43 @@ + +class Parser + def initialize(filename) + @file = File.open(filename, "r") + @text = '' + @file.each_line do |txt| + @text = @text + txt + end + end + + def array_of_words + @text.split(/\W+/) + end + + def map_words_to_count + array = array_of_words + obj = {} + array.each do |item| + item = item.downcase + obj[item] = obj[item] + 1 if obj[item] != nil + obj[item] = 1 if obj[item] == nil + end + obj + end + + def decreasing_order_word_count + map = map_words_to_count + out_array = [] + map.each do |item| + new_obj = {name: item[0], value: item[1]} + out_array.push new_obj + end + out_array.sort_by {|item| item[:value]}.reverse + end +end + +speechParser = Parser.new './speech.txt' + +map_of_words_and_counts = speechParser.decreasing_order_word_count + +map_of_words_and_counts.each do |item| + puts "#{item[:name]}, #{item[:value]}" +end From b5184f7f06c4f92b3759f88df7d1820afc97ec02 Mon Sep 17 00:00:00 2001 From: maxdignan Date: Sun, 27 Dec 2015 22:34:06 -0500 Subject: [PATCH 2/2] made corrections based on feedback --- parser.rb | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/parser.rb b/parser.rb index 64d1a42..352e448 100644 --- a/parser.rb +++ b/parser.rb @@ -1,10 +1,10 @@ class Parser def initialize(filename) - @file = File.open(filename, "r") + file = File.open(filename, "r") @text = '' - @file.each_line do |txt| - @text = @text + txt + file.each_line do |txt| + @text += txt end end @@ -14,23 +14,21 @@ def array_of_words def map_words_to_count array = array_of_words - obj = {} + hash = {} array.each do |item| item = item.downcase - obj[item] = obj[item] + 1 if obj[item] != nil - obj[item] = 1 if obj[item] == nil + if hash[item] == nil + hash[item] = 1 + else + hash[item] += 1 + end end - obj + hash end def decreasing_order_word_count - map = map_words_to_count - out_array = [] - map.each do |item| - new_obj = {name: item[0], value: item[1]} - out_array.push new_obj - end - out_array.sort_by {|item| item[:value]}.reverse + map_arr = map_words_to_count.to_a + map_arr = map_arr.sort_by {|tuple| tuple[1]}.reverse end end @@ -39,5 +37,5 @@ def decreasing_order_word_count map_of_words_and_counts = speechParser.decreasing_order_word_count map_of_words_and_counts.each do |item| - puts "#{item[:name]}, #{item[:value]}" + puts "#{item[0]} => #{item[1]}" end