我有一个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转换为字符串和数组,因为我认为这可能是问题(类型不匹配)但我不知道从哪里开始。有人可以帮忙吗?
答案 0 :(得分:21)
字符串
中的一个(或多个)值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
顺便说一下,整个条款可能会以更加红宝石的方式重写:
finalStatsFile.puts [ col_date,
col_constant1,
col_appYear,
col_statsDesc,
col_constant2,
col_keyStats,
col_weeklyTotal ].map(&:to_s).join(', ')