考虑如下所示的 CSV 文件。如果贷方/借方字段为空字符串,我想将其更改为 0,然后进行一些处理。
我想出的迂回方式似乎效率低下,因为我读取了 csv 文件,应用转换器,然后将其转换为 CSV::Table 进行处理。有没有办法直接将转换器应用于解析方法?
例如:
csv_data = <<_
Description,Debit,Credit
Eating Out,10,""
_
csv = CSV.new(csv_data, headers: true, converters: :integer)
csv.convert do |field, info|
if info.index == 1
field == "" ? 0 : field
end
if info.index == 2
field == "" ? 0 : field
end
end
table = CSV::Table.new(csv.to_a) #Seems wrong to convert to array
puts table[0]['Debit'] #10
puts table[0]['Credit'] #0
Run Code Online (Sandbox Code Playgroud)