当我运行我的代码,我得到如下:零:NilClass(NoMethodError)错误
cities.rb:70:in `sell_is_valid': undefined method `[]' for nil:NilClass (NoMethodError)
from cities.rb:103
from cities.rb:79:in `each'
from cities.rb:79
下面是该代码:
def sell_is_valid(num, type)
puts "The most loads of #{type} you can sell is #{@train[num]}." #Line 66
puts "How many #{type} would you like to sell?"
prompt; value = gets.chomp.to_i
if @train[num] <= value
@wallet = @wallet + (value * @cities[@current_location][num]) #Line 70
@storage = @storage + value
@train[num] = @train[num] - value
else
puts "You're trying to buy too much!"
end
end
所以后来我所做的就是做了一个看跌期权在线70.
puts @wallet
puts @cities[@current_location][num]
这次在puts @cities [@current_location] [num]行上出现同样的错误。所以我知道这是做什么的。但是,我通过我的代码使用该行。例如,按照我的游戏流程(您必须先购买一些东西,然后才能出售它),在buy_is_valid函数中执行三次完全相同的行,而不会出现问题。我也做了一个数字,它给了我一个有效的数字。它也正在66线正确使用。
有关如何跟踪此问题的任何想法?
EDIT
p @cities
p @current_location
返回
{:new_york=>[2, 25, 12], :chicago=>[18, 12, 2], :dallas=>[16, 12, 4], :omaha=>[16, 5, 5], :seattle=>[2, 29, 16]}
"new_york"
'@ current_location'是 “new_york” 但你在'@ cities'键都是有符号(即':new_york')。索引时将@current_location转换为符号,也许? '@cities [@ current_location.to_sym] ...' – BaronVonBraun
@baaron,看起来是修复它。关闭研究符号! –