如何解决“无法将nil转换为String(TypeError)"在Ruby中读取csv文件时? [英] How to get around "Can't convert nil into String (TypeError)" when reading a csv file in Ruby?
问题描述
我正在开发一个程序,该程序最终将比较两个.csv文件并打印出这两个文件之间的所有差异.但是,当我读取其中一个文件时,目前还无法解决无法将nil转换为String(TypeError)"的问题.
I am working on a program that will eventually compare two .csv files and print out any variances between the two. However, at the moment I can't get past a "can't convert nil into String (TypeError)" when reading one of the files.
这是有问题的csv文件中的示例行:
Here is a sample line from the problematic csv file:
11/13/15,11:31:00,ABCD,4000150097,1321126281700ABCDEF,WR00002440,,,4001,1392,AI,INTERNAL RETURN,INBOUND,,ABCDEF
这是到目前为止的代码:
And here is my code so far:
require 'csv'
class CSVReportCompare
def initialize(filename_data, filename_compare)
puts "setting filename_data=", filename_data
puts "setting compare=", filename_compare
@filename_data = filename_data
@filenam_compare = filename_compare
end
def printData
@data = CSV.read(@filename_data)
puts @data.inspect
end
def printCompareData
@compareData = CSV.read(@filename_compare)
puts @compareData.inspect
end
def compareData
end
end
c1 = CSVReportCompare.new("data.csv", "compare_data.csv")
c1.printData
c1.printCompareData
无论如何,有没有办法解决该错误?
Anyways, is there a way to get around the error?
推荐答案
您的initialize
方法中有错字:
@filenam_compare = filename_compare
#-------^ missing "e"
因此,您设置了错误的实例变量.实例变量在首次使用并初始化为nil
时创建,因此稍后,当您尝试访问@filename_compare
时,将创建名称为正确的实例变量,其值nil
.
So you're setting the wrong instance variable. Instance variables are created when they're first used and initialized to nil
so later, when you try to access @filename_compare
, the instance variable with the correct name is created and has a value of nil
.
这篇关于如何解决“无法将nil转换为String(TypeError)"在Ruby中读取csv文件时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!