i keep getting following error every time run code
undefined method '[]' nilclass: nomethoderror
there 2 classes, lineanalyzer
, solution
class , problem seems in lineanalyzer
calculate_word_frequency
method couldn't find error.
the code shown below:
class lineanalyzer attr_accessor :highest_wf_count, :highest_wf_words, :linescount, :content , :line_number @highest_wf_count = hash.new(0) @highest_wf_words = array.new(0) @content @line_number def initialize(line, line_num) @content = line @line_number = line_num calculate_word_frequency() end def calculate_word_frequency() @content.split.each |word| @highest_wf_count[word.downcase] += 1 end max = 0 @highest_wf_count.each_pair |key, value| if value > max max = value end end word_frequency.each_pair |key, value| if value == max @highest_wf_words << key end end end end class solution attr_accessor :highest_count_across_lines, :highest_count_words_across_lines, :line_analyzers @highest_count_across_lines = hash.new() @highest_count_words_across_lines = hash.new() @line_analyzers = array.new() def analyze_file line_count = 0 x = file.foreach('c:\x\test.txt') x.each |line| line_count += 1 @line_analyzers << lineanalyzer.new(line, line_count) end end end solution = solution.new # expect errors until implement these methods solution.analyze_file
any appreciated.
it looks issue when trying increment word_count first time word seen, hash using doesn't have key, can't increment it. first time key seen, should set 1, , occurrences should increment it:
class lineanalyzer attr_accessor :highest_wf_count, :highest_wf_words, :linescount, :content , :line_number def initialize(line,line_num) @highest_wf_count = hash.new(0) @highest_wf_words = array.new(0) @content = line @line_number = line_num calculate_word_frequency() end def calculate_word_frequency() @content.split.each |word| highest_wf_count.key?(word.downcase) ? @highest_wf_count[word.downcase]+=1 : @highest_wf_count[word.downcase]=1 end max =0 @highest_wf_count.each_pair |key, value| if value > max max = value end end highest_wf_count.each_pair |key, value| if value == max @highest_wf_words << key end end end end class solution attr_accessor :highest_count_across_lines, :highest_count_words_across_lines, :line_analyzers @highest_count_across_lines = hash.new() @highest_count_words_across_lines = hash.new() def analyze_file line_count = 0 x = file.foreach('c:\x\test.txt') x.each{ |line| line_count +=1 line_analyzer << lineanalyzer.new(line,line_count) } puts "line_analyzer: #{line_analyzer.inspect}" end def line_analyzer @line_analyzers ||= array.new end end
Comments
Post a Comment