Search code examples
ruby-on-railsrubycsvexport-to-csv

Converting string to csv


I have a piece of code in Ruby which essentially adds multiple lines into a csv through the use of csv_out << listX I have both a header that I supply in the **options and regular data. And I am having a problem when I try to view the CSV, mainly that all the values are in one row and it looks to me that any software fails to recognize '\n' as a line separator.

Input example:

Make, Year, Mileage\n,Ford,2019,10000\nAudi, 2000, 100000

Output dimensions:

8x1 table

Desired dimensions:

3x3 table

Any idea of how to go around that? Either by replacing '\n' with something or using something else than csv.generate

csv = CSV.generate(encoding: 'UTF=8') do |csv_out|
   csv_out << headers
   data.each do |row|
      csv_out << row.values
   end

Solution

  • The problem seems to be the data.each part. Assuming that data holds the string you have posted, this loop is executed only once, and the string is written into a single row.

    You have to loop over the indivdual pieces of data, for instance with

    data.split("\n").each