1

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
5
  • 1
    Please post your actual code rather than just describing it. Right now I am unclear on the issue you are experiencing because the CSV docs clearly states that the column separator defaults to comma and the row separator defaults to :auto (which includes "\r\n", "\n", and "\r") Commented Nov 3, 2021 at 17:06
  • How do you try to view the CSV? What tool do you use? Commented Nov 3, 2021 at 17:14
  • "any software fails" – which software is that in particular? CSV isn't fully standardized, you might have to adjust col_sep or row_sep. (or set your software's import options) Commented Nov 3, 2021 at 17:14
  • At the moment when I try to copy csv variable (which is a long string) and save it as txt file, software like Excel, Numbers and Google Sheets displays it as one row in 8x1 dimensions Commented Nov 3, 2021 at 17:15
  • @ArthurEdelman maybe you copy those \n literally? Try File.write("cars.csv", csv) to eliminate copy-paste errors. Commented Nov 3, 2021 at 17:51

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Data object in this case is an array of Hashes
Hence, row is a Hash. But << assumes the argument to be either of type String or CSV::row. What do you expect when you pass a Hash? See here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.