Hi I’m trying to read csv file, my code is this:
CSV.foreach(path, {:col_sep => @seperator}) do |row|
#CSV.foreach(File.basename(path), {:col_sep => @seperator}) do |row|
r = Route.new
r.contact_id = contact_id
r.name = row[0]
r.number_range = row[1]
r.rate = row[3].gsub(",", ".").to_f
r.valid_from = DateTime.strptime(row[5], @time_format)
r.currency = @currency
r.save
end
And I’m having a problem in this lines:
r.rate = row[3].gsub(",", ".").to_f
r.valid_from = DateTime.strptime(row[5], @time_format)
I get the errors: undefined method 'gsub' for nil:NilClass and
undefined method `strptime' for nil:NilClass
But I’m completely sure that row[3] and row[5] aren’t nil, any idea about why is it happening? Thanks in advance!
The .gsub() is a String method, so it will only work when the row[3] value is a string. It seems that some of your rows are nil. To avoid this you could add a simple checker for nil values
Again the same error for the next line. so you can change it to:
You say you are sure that the values are not nil, but that’s exactly what the error is saying. It only takes 1 line with a nil value to break the entire script.
You’re also hardcoding the rows 3 and 5. Perhaps you mean different rows? Try testing to make sure that row is equating to exactly what you think it is in IRB. Can you show us what row[3] and row[5] equal?