I'm trying to figure out how to work with the sample data below such
that I can take each time there is a C in the third column and update
the previous D to a P.
An ideas?
I've always got ideas.
>> require "rubygems"
=> false
>> require "faster_csv"
=> true
>> data = <<END_DATA
IM,0000001,D,0,@FRIEDEXT01;IMAGES\00\00;0000001.TIF;2
IM,0000002, ,0,@FRIEDEXT01;IMAGES\00\00;0000002.TIF;2
IM,0000003,D,0,@FRIEDEXT01;IMAGES\00\00;0000003.TIF;2
IM,0000004, ,0,@FRIEDEXT01;IMAGES\00\00;0000004.TIF;2
IM,0000005,C,0,@FRIEDEXT01;IMAGES\00\00;0000005.TIF;2
IM,0000006,D,0,@FRIEDEXT01;IMAGES\00\00;0000006.TIF;2
END_DATA
=> "IM,0000001,D,0,@FRIEDEXT01;IMAGES\000\000;0000001.TIF;2\nIM,0000002, ,0,@FRIEDEXT01;IMAGES\000\000;0000002.TIF;2\nIM,0000003,D,0,@FRIEDEXT01;IMAGES\000\000;0000003.TIF;2\nIM,0000004, ,0,@FRIEDEXT01;IMAGES\000\000;0000004.TIF;2\nIM,0000005,C,0,@FRIEDEXT01;IMAGES\000\000;0000005.TIF;2\nIM,0000006,D,0,@FRIEDEXT01;IMAGES\000\000;0000006.TIF;2\n"
>> parsed = FCSV.parse(data)
=> [["IM", "0000001", "D", "0", "@FRIEDEXT01;IMAGES\000\000;0000001.TIF;2"], ["IM", "0000002", " ", "0", "@FRIEDEXT01;IMAGES\000\000;0000002.TIF;2"], ["IM", "0000003", "D", "0", "@FRIEDEXT01;IMAGES\000\000;0000003.TIF;2"], ["IM", "0000004", " ", "0", "@FRIEDEXT01;IMAGES\000\000;0000004.TIF;2"], ["IM", "0000005", "C", "0", "@FRIEDEXT01;IMAGES\000\000;0000005.TIF;2"], ["IM", "0000006", "D", "0", "@FRIEDEXT01;IMAGES\000\000;0000006.TIF;2"]]
>> changed = parsed.inject(Array.new) do |rows, row|
?> if row[2] == "C" and (d_row = rows.reverse.find { |r| r[2] == "D" })
>> d_row[2] = "P"
>> end
>> rows << row
>> end
=> [["IM", "0000001", "D", "0", "@FRIEDEXT01;IMAGES\000\000;0000001.TIF;2"], ["IM", "0000002", " ", "0", "@FRIEDEXT01;IMAGES\000\000;0000002.TIF;2"], ["IM", "0000003", "P", "0", "@FRIEDEXT01;IMAGES\000\000;0000003.TIF;2"], ["IM", "0000004", " ", "0", "@FRIEDEXT01;IMAGES\000\000;0000004.TIF;2"], ["IM", "0000005", "C", "0", "@FRIEDEXT01;IMAGES\000\000;0000005.TIF;2"], ["IM", "0000006", "D", "0", "@FRIEDEXT01;IMAGES\000\000;0000006.TIF;2"]]
>> puts changed.map { |r| r.to_csv }
IM,0000001,D,0,@FRIEDEXT01;IMAGES;0000001.TIF;2
IM,0000002, ,0,@FRIEDEXT01;IMAGES;0000002.TIF;2
IM,0000003,P,0,@FRIEDEXT01;IMAGES;0000003.TIF;2
IM,0000004, ,0,@FRIEDEXT01;IMAGES;0000004.TIF;2
IM,0000005,C,0,@FRIEDEXT01;IMAGES;0000005.TIF;2
IM,0000006,D,0,@FRIEDEXT01;IMAGES;0000006.TIF;2
=> nil
Hope that helps.
James Edward Gray II
···
On Apr 25, 2007, at 3:45 PM, Geoff wrote: