[英]NoMethodError: undefined method `+' for nil:NilClass
I tried googling and looking through stackoverflow and still couldnt figure out why does it not work.我尝试谷歌搜索并查看stackoverflow,但仍然无法弄清楚为什么它不起作用。 Essentially, this line of code reads in a file.txt and loop through the line of instructions on the text file本质上,这行代码读入 file.txt 并循环遍历文本文件上的指令行
# Load instruction in an array
File.open('file.txt').each do |line|
line_num += 1
array.to_a.push line.split(" ")
end
# Loop through the array of Instructions
array.each do |line|
instruction = line[0]
value = line[1].to_i
This is the error that I got这是我得到的错误
NoMethodError: undefined method `+' for nil:NilClass
method block in <main> in VirtualMemory.rb at line 3
method each in VirtualMemory.rb at line 2
method <main> in VirtualMemory.rb at line 2
You have to initialize your variables.你必须初始化你的变量。
line_num += 1
Unless line_num
is previously defined this will fail, it's basically the same thing as line_num = nil + 1
除非先前定义了line_num
否则这将失败,它与line_num = nil + 1
基本相同
This will also fail if you haven't previously defined array
, and if you had, then there'd be no point calling to_a
.如果您之前没有定义array
,这也会失败,如果您有,那么调用to_a
就没有意义了。
array.to_a.push line.split(" ")
line_num += 1
is equivalent to相当于
line_num = line_num + 1
Since line_num is not defined, it is nil -- the fix would be to initialize it as 0 before opening the file, or you could do something like:由于 line_num 未定义,因此它为零——修复方法是在打开文件之前将其初始化为 0,或者您可以执行以下操作:
array = File.open('file.txt').each.map{ |line| line.split(" ")}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.