当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - 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 [email protected] 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 [email protected]

or

for i in [email protected]
网友答案:

The reason is that you use [email protected] range but you have to use [email protected]. 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
分享给朋友:
您可能感兴趣的文章:
随机阅读: