Ruby CSV - get current line/row number
Ruby 2.6+
Without Headers
CSV.foreach( "data.csv", encoding: "UTF-8" ).with_index do |row, row_number|
puts row_number
end
With Headers
CSV.foreach( "data.csv", encoding: "UTF-8", headers: true ).with_index( 2 ) do |row, row_number|
puts row_number # Starts at row 2, which is the first row after the header row.
end
In Ruby 2.6, $INPUT_LINE_NUMBER
no longer gives you the current line number. What's worse is that it's returning values of 2
and 1
. I'm not sure what that is supposed to represent but it's certainly not the row number. Since it doesn't raise an exception, it can really bite you if you're not checking that value. I highly recommend you replace all occurrences of $INPUT_LINE_NUMBER
in your code to avoid this gotcha.
Not a clean but a simple solution
options = {:encoding => 'UTF-8', :skip_blanks => true}
i = 0
CSV.foreach("data.csv", options) do | row |
puts i
i += 1
end
Because of changes in CSV in current Rubies, we need to make some changes. See farther down in the answer for the original solution with Ruby prior to 2.6. and the use of with_index
which continues to work regardless of the version.
For 2.6+ this'll work:
require 'csv'
puts RUBY_VERSION
csv_file = CSV.open('test.csv')
csv_file.each do |csv_row|
puts '%i %s' % [csv_file.lineno, csv_row]
end
csv_file.close
If I read:
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
The code results in this output:
2.6.3
1 ["Year", "Make", "Model", "Description", "Price"]
2 ["1997", "Ford", "E350", "ac, abs, moon", "3000.00"]
3 ["1999", "Chevy", "Venture \"Extended Edition\"", "", "4900.00"]
4 ["1999", "Chevy", "Venture \"Extended Edition, Very Large\"", "", "5000.00"]
5 ["1996", "Jeep", "Grand Cherokee", "MUST SELL!\\nair, moon roof, loaded", "4799.00"]
The change is because we have to get access to the current file handle. Previously we could use the global $.
, which always had a possibility of failure because globals can get stomped on by other sections of called code. If we have the handle of the file being opened, then we can use lineno
without that concern.
$.
Ruby prior to 2.6 would let us do this:
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
with the code above, I get:
1
2
3
4
5
$INPUT_LINE_NUMBER
$.
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
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
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
Which, when run, outputs:
$ 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"
Here's an alternative solution:
options = {:encoding => 'UTF-8', :skip_blanks => true}
CSV.foreach("data.csv", options).with_index do |row, i|
puts i
end