Trenton Tyler Trenton Tyler - 5 months ago 24
Ruby Question

Generate CSV from Ruby results

I currently have this script that generates usernames from a given CSV. Rather than printing these results to the console, how can I write a new CSV with these results?

This is the script I currently have, runs with no errors. I am assuming if I write a new CSV in the do |row| block it is going to create x amount of new files which I do not want.

require 'csv'

CSV.foreach('data.csv', :headers => true) do |row|
id = row['id']
fn = row['first_name']
ln = row['last_name']
p fn[0] + ln + id[3,8]
end

Answer Source

Just manage the CSV file to write around the reading:

CSV.open("path/to/file.csv", "wb") do |csv|
  CSV.foreach('data.csv', :headers => true) do |row|
    id = row['id']
    fn = row['first_name']
    ln = row['last_name']
    csv << [fn[0], ln, id[3,8]]
    # or, to output it as a single column:
    # csv << ["#{fn[0]}#{ln}#{id[3,8]}"]
  end
end

Writing CSV to a file.