【发布时间】:2015-09-25 17:48:54
【问题描述】:
我每次运行代码时都会收到以下错误
undefined method '[]' for nilClass: NoMethodError
有两个类,LineAnalyzer 和 Solution 类,问题似乎出在 LineAnalyzer calculate_word_frequency 方法中,但我找不到错误。
代码如下:
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
任何帮助将不胜感激。
【问题讨论】:
-
你在哪里声明
word_frequencyword_frequency.each_pair do |key, value| -
word_frequency 应该是@highest_wf_count ... 代码错误
-
我认为你是在混合类实例变量和实例变量,希望这个链接可以帮助你stackoverflow.com/questions/15773552/…。基本上,您将@highest_wf_words 声明为类实例变量,并且您试图将其用作实例变量,这就是您收到该错误的原因,因为在@highest_wf_count[word.downcase]+=1 行中,变量被声明为类实例变量。
-
试试
File.open('C:\x\test.txt')
标签: ruby-on-rails ruby class oop