marcamillion marcamillion - 7 months ago 26
Ruby Question

How do I add data in a new column on each row within a CSV?

So I have a method that looks like this:

csvs = Dir["#{@dir_name}/#{@state}/*.csv"]

csvs.each do |csv|
city = csv.split(/[\/]|.csv-updated|.csv/).last
CSV.foreach(csv, headers: true) do |row|
temp = extract_email(row['Website'])
# add result from temp above to existing row

Basically what I want to do is, on each
that I process within the CSV, I want to do something with the data in
(as represented as
in the snippet above), and then I want to take the result and add it as new columns to that row.

So basically I want to append to a each row. How do I do that?


I figured this out.

Basically, I can't edit an existing CSV like that, so I just have to read all the rows from the old_csv and create a new_csv. From that old_csv, I then pass the corresponding data from the old_csv to the method I want (i.e. extract_email(row['Website']) and then I process that info and collect the emails in an array.

From there, all I have to do is iterate over the collection of temp and add it to the row object:

temp.each { |t| row << t }

Then I just add row to the new CSV, which will include the old row + the newly added columns. So in essence I am expanding each row.