[英]Ruby On Rails - NoMethodError: undefined method `[]' for nil:NilClass
[英]Ruby undefined method `[]' for nil:NilClass (NoMethodError) error
从以下代码:
def information_transfer()
file_contents = CSV.read("test.csv", col_sep: ",", encoding: "ISO8859-1")
file_contents2 = CSV.read("applicantinfo.csv", col_sep: ",", encoding:"ISO8859-1")
arraysize = file_contents.length
arraysize1 = file_contents2.length
for i in 1..arraysize
for x in 1..arraysize1
if file_contents[i][0] == file_contents2[x][0]
CSV.open("language_output.csv", "wb") do |csv|
csv << [file_contents[i][0], file_contents[i][1], file_contents[i][2],file_contents[i][3], file_contents[i][4],
file_contents[i][5], file_contents[i][6], file_contents[i][7], file_contents[i][8],file_contents[i][9],
file_contents[i][10], file_contents[i][11], file_contents[i][12], file_contents[i][13], file_contents[i][14],
file_contents[i][15], file_contents[i][16], file_contents[i][17], file_contents[i][18], file_contents2[i][24],file_contents2[i][25],
file_contents2[i][26],file_contents2[i][27], file_contents2[i][28], file_contents2[i][29], file_contents2[i][30], file_contents2[i][31], file_contents2[i][32], file_contents2[i][33]]
end
end
end
end
end
我基本上试图采用两个单独的.csv文件并将某些列合并在一起。 我有两个数组(file_contents和file_contents2)正在读取各个csv文件并将内容存储在数组中。 由于某些原因,我的if语句出现语法错误。 我希望有人可以帮我找出为什么我写的if语句无效。 我想是的。 任何帮助表示赞赏。 谢谢!
您的一个数组file_contents
或file_contents2
可能为空。 在if
语句之前输出两者,以及打印file_contents[i][0]
和file_contents2[x][0]
。
你可以做一个应该工作的简单改变:
for i in 0..arraysize for x in 0..arraysize1
并添加错误检查:
if !file_contents[i].blank? and !file_contents2[x].blank? and file_contents[i][0] == file_contents2[x][0]
for i in 1..arraysize
for x in 1..arraysize1
数组索引在Ruby中从0运行到length - 1; 循环在0...arraysize
而不是。
如果 file_contents2[i]
可以或应该写为file_contents2[x]
,则可以直接遍历数组的内容:
for a in file_contents
for b in file_contents2
并使用切片将连续的数组元素放入另一个数组:
def information_transfer()
file_contents = CSV.read("test.csv", col_sep: ",", encoding: "ISO8859-1")
file_contents2 = CSV.read("applicantinfo.csv", col_sep: ",", encoding: "ISO8859-1")
for a in file_contents
for b in file_contents2
if a[0] == b[0]
CSV.open("language_output.csv", "wb") do |csv|
csv << a[0..18] + b[24..33]
end
end
end
end
end
如果您尝试一对一地加入这两个文件,则可以通过将密钥放入哈希来更有效地实现。 您也可能并不是每次都要重新打开输出文件。
def information_transfer()
file_contents = CSV.read("test.csv", col_sep: ",", encoding: "ISO8859-1")
file_contents2 = CSV.read("applicantinfo.csv", col_sep: ",", encoding: "ISO8859-1")
h = Hash[file_contents.collect { |row| [row[0], row] }]
CSV.open("language_output.csv", "wb") do |csv|
for b in file_contents2
a = h[b[0]]
csv << a[0..18] + b[24..33]
end
end
end
看起来像file_contents
或file_contents2
是空的。
如果您不想在该特定行上引发错误,则可以跳过循环。
next if file_contents[i].blank? || file_contents2[i].blank?
if file_contents[i][0] == file_contents2[x][0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.