Now what I want to do is check for blanks and when I find one I want to
take the info from the entry directly above and fill down the column
until the next blank. Using the above example, I want the following
output:
Now what I want to do is check for blanks and when I find one I want to
take the info from the entry directly above and fill down the column
until the next blank. Using the above example, I want the following
output:
Ok, obiously I'm doing something wrong again. I am new to both
programming and to Ruby, so please excuse the low brow questions!
I've now got this because I really want to take the result and output
to a new file, but it does not work:
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
Thanks, I appreciate it. For some reason the output is the same as the
input when I try this though. Not sure why it does not work.
It occurred to me this morning (what else am I going to think about on
the bus 9^) that since your able to read the file with the
double-quotes, you need to check for missing field using '.empty?'
rather than '= nil'
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