FasterCsv writing columns

M

Mordechai Mr

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
 
J

James Gray

Hi,
Hello.

Can someone help me with FCSV writing ?

I'll sure try.
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 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 }
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 Gray II
 

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

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,144
Latest member
KetoBaseReviews
Top