2

I have a CSV that I parse where I am trying to find a certain row and update a certain column within it. So far I have been able to come up with the query below to find the specific rows that I want to update. But I don't know how to update the csv after this.

So far I have:

csv = CSV.parse(csv_table, :headers => true)

get_persons.each do |person|
  record = csv.find{ |row| row['Email'] == person.email }
  puts record[5]
end

I am able to find the rows that I want to update from the CSV but the problem that I'm stuck on and can't find any help is how do I then update the column for that row that is found (specifically column 6 = record[5]) and add that back into the CSV so that it updates?

Any help would be great, thanks!

luke
  • 1,513
  • 2
  • 20
  • 38
  • Possible duplicate of [How to parse a CSV file, update a field, then save](https://stackoverflow.com/questions/3561278/how-to-parse-a-csv-file-update-a-field-then-save) – Sully May 10 '18 at 19:38

2 Answers2

1

To update the contents, open another file with write mode and put the updated contents there.

CSV.open("write.csv", "wb") do |csv_write|
  CSV.foreach("read.csv") do |row|
     if row['Email'] == "email"
        row[5] = "new email"
     end
     csv_write << row 
  end
end

CSV.parse will load entire contents in memory. If you are reading large files, refer to https://dalibornasevic.com/posts/68-processing-large-csv-files-with-ruby

Sully
  • 14,672
  • 5
  • 54
  • 79
0

This way would work for you?

csv = CSV.parse(csv_table, :headers => true)

get_persons.each do |person|
  record = csv.find do |row| 
    if row['Email'] == person.email 
       row['...'] = 'new_information'
    end
  end  
end

CSV.open("file.csv", "wb") do |new_csv|
  csv.each do |row|
    new_csv << row
  end
end     
Pedro Gabriel Lima
  • 1,122
  • 1
  • 9
  • 24