Maria Shilva
Maria Shilva

Reputation: 81

Creating a comma seperated csv file in ruby

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

Upvotes: 2

Views: 1081

Answers (2)

the Tin Man
the Tin Man

Reputation: 160553

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.)

Upvotes: 0

mohameddiaa27
mohameddiaa27

Reputation: 3597

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

Upvotes: 3

Related Questions