Ruby CSV – 获取当前行/行号

我试图找出如何从Ruby CSV获取当前行/行号。 这是我的代码:

options = {:encoding => 'UTF-8', :skip_blanks => true} CSV.foreach("data.csv", options, ) do |row, i| puts i end 

但是这似乎并不像预期的那样工作。 有没有办法做到这一点?

$.

Ruby有一个魔术variables$. 这是正在读取的当前文件的行号:

 require 'csv' CSV.foreach('test.csv') do |csv| puts $. end 

如果我读到:

 Year,Make,Model,Description,Price 1997,Ford,E350,"ac, abs, moon",3000.00 1999,Chevy,"Venture ""Extended Edition""","",4900.00 1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00 1996,Jeep,Grand Cherokee,"MUST SELL!\nair, moon roof, loaded",4799.00 

用上面的代码,我得到:

 1 2 3 4 5 

$INPUT_LINE_NUMBER

$. 在Perl中一直使用。 在Ruby中,我们推荐我们用下面的方法来避免它的“神奇”一面:

 require 'english' puts $INPUT_LINE_NUMBER 

如果需要在字段中处理embedded的行结束,则可以通过稍微修改来轻松处理。 假设一个CSV文件“test.csv”包含一行embedded的换行符:

 Year,Make,Model,Description,Price 1997,Ford,E350,"ac, abs, moon",3000.00 1999,Chevy,"Venture ""Extended Edition""","",4900.00 1996,Jeep,Grand Cherokee,"MUST SELL! air, moon roof, loaded",4799.00 1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00 

with_index

使用枚举器的with_index(1)可以很容易地跟踪CSV输出到块的次数,有效地使用$.模拟$. 但在阅读处理行结束所需的额外行时,要尊重CSV的工作:

 require 'csv' CSV.foreach('test.csv', headers: true).with_index(1) do |row, ln| puts '%-3d %-5s %-26s %s' % [ln, *row.values_at('Make', 'Model', 'Description')] end 

运行时输出:

 $ ruby test.rb 1 Ford E350 ac, abs, moon 2 Chevy Venture "Extended Edition" 3 Jeep Grand Cherokee MUST SELL! air, moon roof, loaded 4 Chevy Venture "Extended Edition, Very Large" 

这是另一种解决scheme:

 options = {:encoding => 'UTF-8', :skip_blanks => true} CSV.foreach("data.csv", options).with_index do |row, i| puts i end 

不是一个干净而简单的解决scheme

 options = {:encoding => 'UTF-8', :skip_blanks => true} i = 0 CSV.foreach("data.csv", options) do | row | puts i i += 1 end