2

I have array reference like this

a1 = [["http://ww.amazon.com"],["failed"]]

When i write it to csv file it is written like

["http://ww.amazon.com"]
["failed"]

But i want to write like

http://ww.amazon.com   failed
1
  • When you ask a question for help with code, it is really important to show us what code you've written. It's a lot better, and easier, for us to correct your code than it is for us to write something and you try to jam it into place. Commented Nov 4, 2014 at 18:26

2 Answers 2

3

First you need to flatten the array a1

b1 = a1.flatten # => ["http://ww.amazon.com", "failed"]

Then you need to generate the CSV by passing every row (array) to the following csv variable:

require 'csv'
csv_string = CSV.generate({:col_sep => "\t"}) do |csv|
  csv << b1
end

:col_sep =>"\t" is used to insert a tab separator in each row.

Change the value of :col_sep => "," for using comma.

Finally you have the csv_string containing the correct form of the csv

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah it works but how could i add a new line for priniting next array results?
For adding a new row to the csv, all you need is csv << new_row.
0

Ruby's built-in CSV class is your starting point. From the documentation for writing to a CSV file:

CSV.open("path/to/file.csv", "wb") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

For your code, simply flatten your array:

[['a'], ['b']].flatten # => ["a", "b"]

Then you can assign it to the parameter of the block (csv) which will cause the array to be written to the file:

require 'csv'

CSV.open('file.csv', 'wb') do |csv|
  csv << [["row"], ["of"], ["CSV"], ["data"]].flatten
end

Saving and running that creates "file.csv", which contains:

row,of,CSV,data

Your question is written in such a way that it sounds like you're trying to generate the CSV file by hand, rather than rely on a class designed for that particular task. On the surface, creating a CSV seems easy, however it has nasty corner cases and issues to be handled when a string contains spaces and the quoting character used to delimit strings. A well-tested, pre-written class can save you a lot of time writing and debugging code, or save you from having to explain to a customer or manager why your data won't load correctly into a database.

But that leaves the question, why does your array contain sub-arrays? Usually that happens because you're doing something wrong as you gather the elements, and makes me think your question should really be about how do you avoid doing that. (It's called an XY problem.)

Comments

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.