Noah Clark
Noah Clark

Reputation: 8131

nil:NilClass (NoMethodError) Error

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"

Upvotes: 0

Views: 7632

Answers (3)

Andrew Grimm
Andrew Grimm

Reputation: 81490

If you use hash.fetch() rather than hash[], then you'd get an exception when the key doesn't exist, rather than getting nil.

To debug further, I'd do

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

Upvotes: 0

sepp2k
sepp2k

Reputation: 370112

The error message is saying, that you're calling [] on nil. Since in the expression @cities[@current_location][num], you're first calling [] on @cities and then on the result of @cities[@current_location], this means that either @cities or @cities[@current_location] is nil.

To find out which one is the case, you should trying printing out @cities and @current_location using p @cities, @current_location. If @cities is nil, that's the reason for the error. If it isn't it should now at least be apparent why @current_location isn't a valid key for it.

Upvotes: 2

Platinum Azure
Platinum Azure

Reputation: 46183

Either @cities is nil, or @cities[@current_location] is nil.

Figure out which one it is and then find a way to make sure it's populated. :-)

Upvotes: 2

Related Questions