Create a CSV file for illustration.
File.write('t.csv', <<~END
Now,is,the
time,for,all
good,Rubiests,to
come,to,the
aid,of,their
bowling,team,.
END
)
Let's look at it.
puts File.read('t.csv')
Now,is,the
time,for,all
good,Rubiests,to
come,to,the
aid,of,their
bowling,team,.
Then if rows whose indices are in the range rng
are to be skipped,
require 'csv'
rng = 1..3
CSV.foreach('t.csv').reject.with_index { |_,i| rng.cover?(i) }
#=> [["Now", "is", "the"],
# ["aid", "of", "their"],
# ["bowling", "team", "."]]
Use select
rather than reject
if desired.
More generally, if rows whose indices are in an array arr
are to be skipped,
arr = [1, 3, 4]
CSV.foreach('t.csv').reject.with_index { |_,i| arr.include?(i) }
#=> [["Now", "is", "the"],
# ["good", "Rubiests", "to"],
# ["bowling", "team", "."]]
One could also write the following.
arr = [1, 3, 4]
x, y = CSV.foreach('t.csv').partition.with_index { |_,i| arr.include?(i) }
x #=> [["time", "for", "all"], ["come", "to", "the"], ["aid", "of", "their"]]
y #=> [["Now", "is", "the"], ["good", "Rubiests", "to"], ["bowling", "team", "."]]