tags:

views:

21

answers:

1

I have everything working fine except saving my changes to the field im updating:

require 'csv'
@parsed_file = CSV::Reader.parse(File.open("#{RAILS_ROOT}/doc/some.csv"))
@parsed_file.each_with_index  do |row, x|
  address = row[5]
  l = Location.address_find(address)
  if l != nil
    puts "#{l.name} at #{l.address}"
    row[14] = l.store_code
    puts row[14]
  else
    puts "No matching address Found!!!"
  end
  #What do I do here? Something like this? CSV::Writer.generate(@parsed_file) 
end

What do I do Here? how do I save the changes I made and update the file?

+2  A: 

What I would do is write the updated records to a new file and then, if you want, after you have finished your program can delete the old file and rename the new file to have the original file name.

To do this I would open the output file at the top of your code, outside the each_with_index loop. e.g.

csv_out = CSV::Writer.generate(File.open('new.csv', 'wb'))

Then inside your each_with_index loop you can write the current row to the new file like this:

csv_out << row

Then at the end you can close the new file:

csv_out.close
mikej
would I csv_out.close outside the loop?
jtmkrueger
Yep, the `csv_out.close` would be outside the `each_with_index` loop as you only want to do this once and after you have finished looping over the rows from the original file.
mikej
That makes sense, Thanks!
jtmkrueger