获取错误未定义方法`[]'为nil:NilClass(NoMethodError)

时间:2017-07-06 06:44:56

标签: ruby-on-rails ruby

这是代码

class Tech
  attr_reader :content, :tech_hash
  @tech_hash = Hash.new(0)
  def initialize(content)
    @content = content
    showTech(content)
  end
  def showTech(content)
    content.split.each do |word|
    @tech_hash[word] += 1
    end
    @tech_hash = @tech_hash.sort_by{|k,v| -v}.to_h
    p @tech_hash
  end
end

class Digital
  def analyze()
    File.foreach('test.txt') do |content|
      ob = Tech.new(content)
    end
  end
end

digi = Digital.new()
digi.analyze()

这是错误

D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:10:in `block in showTech': undefined method `[]' for nil:NilClass (NoMethodError)
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:9:in `each'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:9:in `showTech'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:6:in `initialize'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:22:in `new'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:22:in `block in analyze'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:20:in `foreach'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:20:in `analyze'
    from D:/graded-assignments/course01/module02/assignment-Calc-Max-Word-Freq/Tech.rb:29:in `<main>'

1 个答案:

答案 0 :(得分:1)

@tech_hash是在实例方法之外定义的,是什么使它成为类变量。因此,在showTech内,仍然没有定义@tech_hash个实例变量,因此返回nil

只需将@tech_hash移到initialize方法中即可初始化实例变量:

def initialize(content)
  @content = content
  @tech_hash = Hash.new(0)

  showTech(content)
end