From: Jeffrey Schwab Date: 2006-03-16T23:38:47+09:00 Subject: Re: csv nil check and update Geoff wrote: > require 'CSV' > > last = "" > newFile = File.open("C:\\temp\\geoff\\filldown\\filldownNew.txt", "w+") > CSV.foreach("C:\\temp\\geoff\\filldown\\filldown.txt") do |row| > if row[-1].empty? > row[-1] = last > else > last = row[-1] > end > newFile << (p row) > end Do you need to preserve the redundant quotes in the output? If not, this might be what you want: # vim:ts=4 sw=4 et require 'CSV' last = '' out_csv = CSV.open('output.csv', 'w') CSV.foreach('input.csv') do |row| if row[-1].empty? row[-1] = last else last = row[-1] end out_csv << row end out_csv.close If it were me, I would probably group the datum "last" and the functionality that dealt with it into a separate object, at the expense of longer code. Maybe it's premature factoring, but I can just see that loop body getting more complicated as you want to do more with it, like replacing all blank fields (instead of just the last one) with previously read values. # vim:ts=4 sw=4 et require 'CSV' class BlankFiller def initialize(last='') @last = last end def fill(e) if e.empty? e = @last else @last = e end end end blank_filler = BlankFiller.new out_csv = CSV.open('output.csv', 'w') CSV.foreach('input.csv') do |row| row[-1] = blank_filler.fill(row[-1]) out_csv << row end out_csv.close