2011-08-22 75 views
0

当我运行我的代码,我得到如下:零: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" 
+1

'@ current_location'是 “new_york” 但你在'@ cities'键都是有符号(即':new_york')。索引时将@current_location转换为符号,也许? '@cities [@ current_location.to_sym] ...' – BaronVonBraun

+0

@baaron,看起来是修复它。关闭研究符号! –

回答

2

错误消息是说,你打电话[]nil。由于在表达式@cities[@current_location][num]中,您首先在@cities上调用[],然后根据@cities[@current_location]的结果,这意味着@cities@cities[@current_location]nil

要找出哪一种情况,您应该尝试使用p @cities, @current_location打印@cities@current_location。如果@citiesnil,那就是错误的原因。如果不是这样,现在至少应该明白为什么@current_location不是它的有效密钥。

+0

如果@cities不是零,那么它必须是@current_location?我做了每个p,他们返回有效(非零)的声明。查看我编辑的原始问题的结果。 –

+1

@Noah:不,如果'@ cities'为零,事实上不会导致此错误消息。正如我所说:如果'@ cities'不是零,那么'@cities [@current_location]'为零,这意味着'@ current_location'不存在作为'@ cities'中的一个键(或者不是一个有效的索引'@ cities'如果'@ cities'是一个数组)。如果您使用'p'打印'@ cities'和'@ current_location',应该很明显,为什么'@ current_location'不是有效的键/索引。 – sepp2k

+1

@Noah:正如你的编辑所示,“@ current_location”是''new_york“',它不是出现在'@ cities'(':new_york'确实,但不是同一个值)的关键字。您应该将'@ current_location'转换为符号或更改'@ cities'以将字符串用作键而不是符号。 – sepp2k

2

要么@citiesnil,或@cities[@current_location]nil

找出它是哪一个,然后找到一种方法来确保它被填充。 :-)

+0

我相信我用p做了一个有效的测试,而且它们都不是零。有没有更好的方法来做到这一点?请参阅原文中的编辑。 –

+0

@NoahClark:正如您在使用@ sepp2k时发现的,我们在讨论'@ current_location'是'@ cities'中的一个无效键,因此'@cities [@current_location]'是'nil'。这与'@ current_location'为'nil'不同。 –

0

如果您使用的是hash.fetch()而不是hash[],那么当密钥不存在时您将得到异常,而不是获取nil。

为了进一步调试,我会做

hash.fetch(key) {raise "couldn't find #{key.inspect} amongst the keys #{hash.keys.inspect}"} 
相关问题