2015-07-19 102 views
3

这里是我的代码:未定义的方法[]为nil:NilClass(NoMethodError)在ruby中...为什么?

begin 
    items = CSV.read('somefile.csv') 
    linesAmount = CSV.readlines('somefile.csv').size 
    counter = 1 
    while linesAmount >= counter do 
     fullrow = items[counter] 
     firstitem = fullrow[0] #This is the line that my code doesn't like. 
     puts firstitem 
     counter = counter + 1 

    end 


end 

对于一些红宝石不喜欢这一行,在那里我有=与firstItem fullrow [0]。它引发了未定义的方法[]错误。但是,在控制台中,我仍然可以看到它打印第一项...所以它仍然打印它,但仍然会引发错误?这是怎么回事?但是,如果我将while循环的while循环的前三行放在while循环的外部,并注释掉循环中除计数器行以外的所有内容,那么我不会收到任何错误。因此,如果第一行项出现在while循环之外,代码认为它没有问题。

编辑:我知道数组从0开始,但我特别想反击,不关心第一行。我忘了提及那个,对不起。

编辑2:谢谢大家,我通过在linesAmount后面加-1来解决它,它起作用!

+0

数组在红宝石是从零开始的。在'counter == linesAmount'上是'linesAmount + 1'行,'items [counter]'是可以预测的nil。因此'fullrow'是零,因此是一个错误。在控制台中看到的是前一个循环的打印值。顺便说一句,整个代码看起来太麻烦了。 'items.each'在这里更适合。 – mudasobwa

+0

不要在问题中提出答案。 –

回答

1

看起来你有一个错误,你正在阅读物品数组的末尾。如果有10行的CSV文件,该线将与索引数组从0到9,而不是1到10

更改的,同时这个样子

counter = 0 
while counter < linesAmount 
    ... 
end 

但更好的方法整体将只是做以下

CSV.readlines('somefile.csv').each do |line| 
    puts line 
end 
+0

condition'counter <= linesAmount'将运行0..10,仍然引发异常。 – BroiSatse

+1

你是对的,你到达的时间恰好是错误的,我认为在我编辑纠正它之前大约20秒。 – Marc

1

CSV.readCSV.readlines返回数组。如果您的数组包含两个值,则size返回2。但是您需要拨打的索引是items[0]和项目[1]。因此,此行

items[counter] 

将引发错误。

行更改为

items[counter - 1] 

,它应该工作。

此外,您可以通过使用Ruby的成语提高代码:

begin 
items = CSV.read('somefile.csv') 
items.each do |item| 
    puts item[0] 
end 
end 
相关问题