繁体   English   中英

undefined方法[]为nil:ruby中的NilClass(NoMethodError)...为什么?

[英]undefined method [] for nil:NilClass (NoMethodError) in ruby… Why?

这是我的代码:

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]。 它抛出了未定义的方法[]错误。 但是,在控制台中,我仍然可以看到它打印firstitem ...所以它仍然打印它,但却抛出错误? 这是怎么回事?

但是,如果我在while循环的while循环OUTSIDE中取前三行,并注释除了计数行以外的循环中的所有内容,那么我不会收到任何错误。 因此,如果firstitem行出现在while循环之外,代码认为它一切正常。

编辑:我知道数组从0开始,但我特别希望反对不关心第一行。 我忘了提,抱歉。

Edit2:谢谢大家,我在linesAmount之后添加-1解决了它,它的工作原理!

看起来你有一个错误,你正在阅读items数组的结尾。 如果CSV文件中有10行,则这些行将是索引从0到9而不是1到10的数组。

改变你的时间看起来像这样

counter = 0
while counter < linesAmount
  ...
end

然而,总体上更好的方法是执行以下操作

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

CSV.readCSV.readlines返回数组。 如果数组包含两个值,则size返回2 但是你需要调用的索引是items[0]和items [1]。 所以这一行

items[counter]

抛出错误。

将行更改为

items[counter - 1]

它应该工作。

此外,您可以使用Ruby习语改进代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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