3

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?

toro2k
  • 19,020
  • 7
  • 64
  • 71
ZK Zhao
  • 19,885
  • 47
  • 132
  • 206
  • That's not a duplicate question. This question is about how to get a RANGE of lines - not a line NUMBER. That's a different thing. – prograils Oct 19 '18 at 08:42

1 Answers1

4

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
toro2k
  • 19,020
  • 7
  • 64
  • 71