# FasterCsv writing columns

**URL:** <https://www.ruby-forum.com/t/fastercsv-writing-columns/154766>\
**Category:** Ruby\
**Created:** [December 3, 2008, 6:21pm UTC](https://www.ruby-forum.com/t/fastercsv-writing-columns/154766 "2008-12-03T18:21:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![marcisco0](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/3da27b/32.png) [@marcisco0](https://www.ruby-forum.com/u/marcisco0)\
**Post date:** [December 3, 2008, 6:21pm UTC](https://www.ruby-forum.com/t/fastercsv-writing-columns/154766/1 "2008-12-03T18:21:26Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![marcisco0](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/3da27b/32.png) [@marcisco0](https://www.ruby-forum.com/u/marcisco0)\
**Post date:** [December 3, 2008, 9:14pm UTC](https://www.ruby-forum.com/t/fastercsv-writing-columns/154766/2 "2008-12-03T21:14:07Z")

</div>

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
