gpt4 book ai didi

ruby - 无方法错误 : undefined method `+' for nil:NilClass

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:48 26 4
gpt4 key购买 nike

我尝试使用谷歌搜索并查看 stackoverflow,但仍然无法弄清楚为什么它不起作用。本质上,这行代码读入一个 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

这是我得到的错误

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

最佳答案

line_num += 1

相当于

line_num = line_num + 1

因为 line_num 没有定义,所以它是 nil —— 修复方法是在打开文件之前将它初始化为 0,或者你可以这样做:

array = File.open('file.txt').each.map{ |line| line.split(" ")}

关于ruby - 无方法错误 : undefined method `+' for nil:NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41860566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com