For example, maybe I want to start from the 5th row:
csv_text = File.read(file)
csv = CSV.parse(csv_text, :headers => true)
csv[20..-1].each do |row|
end
Is it possible to write something like csv[5..-1]
, from the 5th to the last row?
For example, maybe I want to start from the 5th row:
csv_text = File.read(file)
csv = CSV.parse(csv_text, :headers => true)
csv[20..-1].each do |row|
end
Is it possible to write something like csv[5..-1]
, from the 5th to the last row?
You can use the CSV.foreach
method to iterate over the CSV and the with_index
method to count the rows you read and skip rows you don't want to process. For example:
require 'csv'
CSV.foreach(file, headers: true).with_index(1) do |row, rowno|
next if rowno < 5 # skips first four rows
# process the row
end
In Ruby 1.9.3 this wouldn't work since foreach
doesen't return an Enumerator
if no block is given. The code can be modified like this:
CSV.to_enum(:foreach, file, headers: true).with_index(1) do |row, rowno|
# ...
end