Graham Slick
Graham Slick

Reputation: 6870

Remove row of a CSV file based on the index by iterating over the rows

I have a CSV file, and I want to remove a row at a particular index.

CSV.foreach(@filepath, @csv_options) do |row|
    # delete row if row's index == n 
end

I found alternative solutions by storing the CSV file in a @file variable and by doing @file.delete_at(n) but it won't actually delete it from the CSV file. I thought of erasing the CSV file and copying what's stored in @file but that seems way too complicated.

Is there a way to do it directly from the CSF file ?

Upvotes: 0

Views: 556

Answers (1)

ssuljic
ssuljic

Reputation: 1081

The thing you thought of is not complicated, just rewrite the file.

File.open(@filepath, 'w') { |f| f.puts(@file) }

Upvotes: 1

Related Questions