create a csv file in ruby

To create a CSV file in Ruby, you can use the CSV standard library which provides a simple interface for working with CSV files.

First, you need to require the CSV library:

main.rb
require 'csv'
14 chars
2 lines

Then, you can write an array of data to a CSV file using the CSV.open method:

main.rb
data = [
  ['John', 'Doe', 30],
  ['Alice', 'Smith', 25],
  ['Bob', 'Johnson', 42]
]

CSV.open('people.csv', 'w') do |csv|
  data.each do |row|
    csv << row
  end
end
169 chars
12 lines

In the example above, we create an array of arrays, where each inner array represents a row of data. We then use CSV.open to create a new CSV file named "people.csv" in write mode ('w'). We iterate over each row of data, and for each row, we add it to the CSV file using the << operator.

This will create a CSV file with the following content:

main.rb
John,Doe,30
Alice,Smith,25
Bob,Johnson,42
42 chars
4 lines

You can also pass additional options to CSV.open to configure things like the delimiter character and row separator. Check out the documentation for more information.

gistlibby LogSnag