append to a csv file in ruby

To append to a CSV file in Ruby, you can use the CSV library to open the file in "append" mode and then write to it using the << operator. Here's an example:

main.rb
require 'csv'

# Open the CSV file in append mode
CSV.open('file.csv', 'a') do |csv|

  # Array of values to append to the CSV file
  values = ['John Smith', 'john@example.com', '123 Main St.']

  # Append the values to the CSV file
  csv << values
end
253 chars
12 lines

In this example, we're opening the file file.csv in "append" mode using CSV.open. Then, we define an array of values to append to the file. Finally, we use the << operator to append the values to the file. The CSV.open block takes care of closing the file for us.

related categories

gistlibby LogSnag