Forum: Ruby FasterCsv writing columns

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Isley B. (Guest)
on 2008-12-03 19:21
Hi,

Can someone help me with FCSV writing ?

If I have an array of integers lets say
someList[0].listName = "header1"
someList[0].someArray = [ 2, 4, 8, 9 ]

someList[1].listName = "header2"
someList[1].someArray = [ 10, 11, 12, 13 ]

I'm desperately trying to figure out how to use FasterCSV to produce a
csv file that will show:

header1, header2
2,  10,
4,  11,
8,  12,
9,  13,
header1_avg,header2_avg

I've read through the FasterCSV documents, and I just can't figure
things out.  I know I most likely need to use the FCSV table, or read
the array in and use the FCSV.parse...

Thanks for your help.
mord
James G. (Guest)
on 2008-12-03 22:14
(Received via mailing list)
On Dec 3, 2008, at 11:15 AM, Mordechai Mr wrote:

> Hi,

Hello.

> Can someone help me with FCSV writing ?

I'll sure try.

> header1, header2
> 2,  10,
> 4,  11,
> 8,  12,
> 9,  13,
> header1_avg,header2_avg

I would use code like:

#!/usr/bin/env ruby -wKU

require "rubygems"
require "faster_csv"

Column  = Struct.new(:header, :data) do
   def average
     return 0 if data.empty?
     data.inject(0) { |sum, n| sum + n } / data.size
   end
end
columns = [ Column.new("header1", [2, 4, 8, 9]),
             Column.new("header2", [10, 11, 12, 13]) ]

FCSV do |csv|
   csv << columns.map { |c| c.header }
   columns.map { |c| c.data.size }.max.times do |i|
     csv << columns.map { |c| c.data[i] }
   end
   csv << columns.map { |c| c.average }
end

__END__

That spits the data to STDOUT.  If you would rather send it to a file,
just change this line:

FCSV do |csv|

to:

FCSV.open("my_file_name.csv", "w") do |csv|

> I've read through the FasterCSV documents, and I just can't figure
> things out.  I know I most likely need to use the FCSV table, or read
> the array in and use the FCSV.parse...

Na.  These methods are for reading CSV data, not writing it.

Hope that helps.

James Edward G. II
This topic is locked and can not be replied to.