I keep getting the following error every time I run my code
undefined method '[]' for nilClass: NoMethodError
There are two classes, LineAnalyzer
and Solution
class and the problem seems to be in the LineAnalyzer
calculate_word_frequency
method but I couldn't find the error.
The code is as 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 do |word|
@highest_wf_count[word.downcase] += 1
end
max = 0
@highest_wf_count.each_pair do |key, value|
if value > max
max = value
end
end
word_frequency.each_pair do |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 do |line|
line_count += 1
@line_analyzers << LineAnalyzer.new(line, line_count)
end
end
end
solution = Solution.new
# Expect errors until you implement these methods
solution.analyze_file
Any help would be appreciated.