Ruby CSV - 获取当前行/行号 [英] Ruby CSV - get current line/row number
问题描述
我试图找出如何从Ruby CSV获取当前行/行号。这是我的代码:
I'm trying to work out how to get the current line/row number from Ruby CSV. This is my code:
options = {:encoding => 'UTF-8', :skip_blanks => true}
CSV.foreach("data.csv", options, ) do |row, i|
puts i
end
但这似乎没有按预期工作。有没有办法做这个?
But this doesn't seem to work as expected. Is there a way to do this?
推荐答案
Ruby有一个变量变量 $。
,这是要读取的当前文件的行号:
Ruby has a magic variable $.
which is the line number of the current file being read:
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
$。
始终在Perl中使用。在Ruby中,建议我们使用以下方式避免它的神奇一面:
$.
is used all the time in Perl. In Ruby, it's recommended we use it the following way to avoid the "magical" side of it:
require 'english'
puts $INPUT_LINE_NUMBER
如果需要处理字段中嵌入的行末尾,则很容易通过小修改来处理。假设有一个CSV文件test.csv,其中包含一行带有嵌入的新行:
If it's necessary to deal with embedded line-ends in fields, it's easily handled by a minor modification. Assuming a CSV file "test.csv" which contains a line with an embedded new-line:
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(1)
可以很容易地跟踪CSV对块产生的次数,使用 $。
,但是在读取处理行末尾所需的额外行时尊重CSV的工作:
Using Enumerator's with_index(1)
makes it easy to keep track of the number of times CSV yields to the block, effectively simulating using $.
but honoring CSV's work when reading the extra lines necessary to deal with the line-ends:
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"
这篇关于Ruby CSV - 获取当前行/行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!