From: Pen Ttt on
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?
--
Posted via http://www.ruby-forum.com/.

From: Chen Ge on
Pen Ttt wrote:
> 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
--
Posted via http://www.ruby-forum.com/.

From: Brian Candler on
Pen Ttt wrote:
> 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)
--
Posted via http://www.ruby-forum.com/.