简体   繁体   中英

Undefined method '[ ]' for nil:NilClass <NoMethodError>

Help me pls, i got that NoMethodError when im trying to execute this method

def traspuesta()
i=0
aux=nil
    for i in 0..@lt.length do
            aux = @lt[i][0]
            @lt[i][0] = @lt[i][1]
            @lt[i][1] = aux
    end
end

the full error says this:

Undefined method '[]' for nil:NilClass <NoMethodError>
from MDListaTrip.rb:83:in 'each'
from MDListaTrip.rb:83:in 'traspuesta'
from MDListaTrip.rb:111:in '<main>'

Use

for i in 0...@lt.length

or

for i in 0..@lt.length-1

The reason is that you use 0..@lt.length range but you have to use 0..@lt.length-1 . Because of this your last item is nil. And nil object does not respond to [] method. That's why you get your error.

To prevent this you can use iterator:

@lt.each do |item|
  aux = item[0]
  item[0] = item[1]
  item[1] = aux
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM