Undefined method [] for nil: NilClass (NoMethodError) in ruby ββ... Why?
Here's my code:
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
For some ruby ββdon't like this one line where I have firstitem = fullrow [0]. This throws an undefined method [] error. BUT, in the console, I can still see that it prints the first item ... So it still prints it, but still throws an error? What's happening?
However, if I take the first three lines during the OUTSIDE of the while loop and comment everything out in a loop other than the counter line, then I don't get any errors. So if this line firstitem appears outside of the while loop, the code thinks everything is fine.
Edit: I know that arrays start at 0, but I specifically wanted the counter not to care about the very first line. I forgot to mention this, sorry.
Edit2: Thanks everyone, I solved this by adding -1 after linesAmount and it works!
source to share
It looks like you have one error, you are reading it past the end of the array of elements. If the CSV file has 10 lines, the lines will be an array with indices from 0 to 9, not from 1 to 10.
Change the time to look like this.
counter = 0 while counter < linesAmount ... end
However, the best approach overall would be as follows:
CSV.readlines('somefile.csv').each do |line|
puts line
end
source to share
CSV.read
and CSV.readlines
return arrays. If your array contains two values, then it size
returns 2
. But the indexes you need to call items[0]
are items [1]. Therefore this line
items[counter]
gives an error message.
Change the line to
items[counter - 1]
and it should work.
Alternatively, you can improve your code using Ruby idioms:
begin
items = CSV.read('somefile.csv')
items.each do |item|
puts item[0]
end
end
source to share