write to a csv file in ruby

To write to a CSV file in Ruby, you can use the built-in CSV library.

Here's an example:

main.rb
require 'csv'

# Open the CSV file for writing
CSV.open('file.csv', 'wb') do |csv|
  
  # Write the header row
  csv << ['Name', 'Email', 'Phone']

  # Write some data rows
  csv << ['John Doe', 'john@example.com', '555-1234']
  csv << ['Jane Smith', 'jane@example.com', '555-5678']
end
287 chars
13 lines

The CSV.open method takes two arguments: the filename to write to, and a file mode (in this case, 'wb' for "write binary").

You can then pass data to the CSV writer using the << operator. Each call to << writes a new row to the CSV file.

In this example, we write a header row with the column names, and two data rows with sample data.

When you're finished writing to the CSV file, be sure to close it using the close method:

main.rb
csv.close
10 chars
2 lines

That's all there is to it!

gistlibby LogSnag