没有将 nil 隐式转换为 String 错误

no implicit conversion of nil into String error

我有一个 ruby 脚本,它将通过获取和合并来自另一个文件的值来创建两个文件。

#Resources
require 'rubygems'
require 'csv'

col_date = []
col_constant1 = []
col_constant2 = []
col_appYear = []
col_statsDesc = []
col_keyStats =[]
col_weeklyTotal=[]


weekly_total = []

fname = "finalStats.csv" #variable for capture file
        finalStatsFile = File.open(fname, "w") #write to capture file
fname2 = "weeklyStats.csv"
        weeklyStatsFile = File.open(fname2, "w")    
CSV.foreach('compareData.csv', converters: :numeric) do |row|
    weekly_total << row[0] - row[1]

    weekly_total.each do |data| 
    data << weekly_total.shift 
     weeklyStatsFile.puts data
end 
end

#retrieve stats from original document 
 CSV.foreach("autoCapture.csv") {|row| col_date << row[0]}
 CSV.foreach("autoCapture.csv") {|row| col_constant1 << row[1]}
 CSV.foreach("autoCapture.csv") {|row| col_appYear << row[2]}
 CSV.foreach("autoCapture.csv") {|row| col_statsDesc << row[3]}
 CSV.foreach("autoCapture.csv") {|row| col_constant2 << row[4]}
 CSV.foreach("autoCapture.csv") {|row| col_keyStats << row[5]}
 CSV.foreach("weeklyStats.csv") {|row| col_weeklyTotal << row[0]}



  col_date.zip(col_constant1, col_appYear, col_statsDesc, col_constant2, col_keyStats, col_weeklyTotal).each do |col_date, col_constant1, col_appYear, col_statsDesc, col_constant2, 
  col_keyStats, col_weeklyTotal|

  finalStatsFile.puts col_date+", "+col_constant1+", "+ col_appYear+", "+col_statsDesc+", "+col_constant2+", "+col_keyStats+", "+col_weeklyTotal

 end

在一个文件中,我希望从行[0] 中的值中减去行[1] 中的值以创建一个新的'weekly_total' 值。然后我将这个值数组输出到一个名为 weeklyStats.csv 的文件中。这将输出一列值。

但是,我想将这些值与另一个文件 (autoCapture.csv) 中的另一个集合连接起来,当我尝试将它们压缩为数组以便它们在相应的行中读取时,我得到了错误:

weeklyStats_csv.rb:42:in `+': no implicit conversion of nil into String (TypeError)
    from weeklyStats_csv.rb:42:in `block in <main>'
    from weeklyStats_csv.rb:40:in `each'
    from weeklyStats_csv.rb:40:in `<main>'

我认为这意味着如果其中一个值为 nil 则数组 zip 将不会捕获异常,因此无法转换为字符串。问题是,我已经尝试将 weekly_total 转换为字符串和数组,因为我认为这可能是问题所在(类型不匹配),但我只是不知道从这里去哪里。有人可以帮忙吗?

字符串中的一个(或多个)值

finalStatsFile.puts col_date+", "+col_constant1+", "+ col_appYear+", "+col_statsDesc+", "+col_constant2+", "+col_keyStats+", "+col_weeklyTotal

变成了nil。要修复输出,您应该将它们显式转换为字符串:

finalStatsFile.puts col_date.to_s + ", " + 
                    col_constant1.to_s + ", " + 
                    col_appYear.to_s + ", " + 
                    col_statsDesc.to_s + ", " +
                    col_constant2.to_s + ", " +
                    col_keyStats.to_s + ", " + 
                    col_weeklyTotal.to_s 

顺便说一句,整个子句可能会以更像 ruby​​ish 的方式重写:

finalStatsFile.puts [ col_date,
                      col_constant1,
                      col_appYear,
                      col_statsDesc,
                      col_constant2,
                      col_keyStats,
                      col_weeklyTotal ].map(&:to_s).join(', ')