how to write array value into csv file?

P

Pen Ttt

how to write array value into csv file?
there is array a:
a[0]=date;asset;cash;finance;note;
a[1]=2009-12-31;580;1,693;201;500;
a[2]=2009-09-30; 680;1,777;2497;700;
i want to get array a into csv files as the following:

csvfile1:
date 2009-12-31 2009-09-30
asset 580 680
cash 1,693 1,777
finance 201 2497
note 500 700
csvfile2:
date asset cash finance note
2009-12-31 580 1,693 201 500
2009-09-30 680 1,777 2497 700

how can i do?
 
C

Chen Ge

Pen said:
how to write array value into csv file?
there is array a:
a[0]=date;asset;cash;finance;note;
a[1]=2009-12-31;580;1,693;201;500;
a[2]=2009-09-30; 680;1,777;2497;700;
i want to get array a into csv files as the following:

csvfile1:
date 2009-12-31 2009-09-30
asset 580 680
cash 1,693 1,777
finance 201 2497
note 500 700
csvfile2:
date asset cash finance note
2009-12-31 580 1,693 201 500
2009-09-30 680 1,777 2497 700

how can i do?



a=[]
a[0]='date;asset;cash;finance;note;'
a[1]='2009-12-31;580;1,693;201;500;'
a[2]='2009-09-30; 680;1,777;2497;700;'


file=File.new('csv2.csv','w')
for e in a do
str_array=e.split(';')
for x in str_array do
file.write x + "\t\t\t"
end
file.puts
end

#output to csv2 file
 
B

Brian Candler

Pen said:
how to write array value into csv file?
there is array a:
a[0]=date;asset;cash;finance;note;
a[1]=2009-12-31;580;1,693;201;500;
a[2]=2009-09-30; 680;1,777;2497;700;
i want to get array a into csv files as the following:

csvfile1:
date 2009-12-31 2009-09-30
asset 580 680
cash 1,693 1,777
finance 201 2497
note 500 700
csvfile2:
date asset cash finance note
2009-12-31 580 1,693 201 500
2009-09-30 680 1,777 2497 700

how can i do?

I'd suggest parsing the data first so that each element of a is itself
an array of values. That makes it very easy to handle:

a=[]
a[0]="date;asset;cash;finance;note;"
a[1]="2009-12-31;580;1,693;201;500;"
a[2]="2009-09-30; 680;1,777;2497;700;"
b = a.map { |elem| elem.split(";") }

require 'fastercsv'
FasterCSV.open("csvfile2","w") do |csv|
b.each { |row| csv << row }
end
FasterCSV.open("csvfile1","w") do |csv|
b.transpose.each { |row| csv << row }
end

Use the :col_sep option to FasterCSV if you want tab-separated values
(TSV) rather than comma-separated values (CSV)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top