When I run my code I get the following:
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
Here is the code for that:
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
So then what I did was did a puts on line 70.
puts @wallet
puts @cities[@current_location][num]
Same error this time on the puts @cities[@current_location][num] line. So I know that is what is making it do this. However, I use that line all through my code. For example, do the to the flow of my game (you have to buy something before you can sell it) that exact same line is executed three times in the buy_is_valid function with no issues. I also did a puts on num and it is giving me a valid number. It also is being used correctly in line 66.
Any ideas on how to track this down?
EDIT
p @cities
p @current_location
returns
{:new_york=>[2, 25, 12], :chicago=>[18, 12, 2], :dallas=>[16, 12, 4], :omaha=>[16, 5, 5], :seattle=>[2, 29, 16]}
"new_york"
The error message is saying, that you’re calling
[]onnil. Since in the expression@cities[@current_location][num], you’re first calling[]on@citiesand then on the result of@cities[@current_location], this means that either@citiesor@cities[@current_location]isnil.To find out which one is the case, you should trying printing out
@citiesand@current_locationusingp @cities, @current_location. If@citiesisnil, that’s the reason for the error. If it isn’t it should now at least be apparent why@current_locationisn’t a valid key for it.