write multiple key/value to a row using cvs library

L

Li Chen

Hi all,

I have a hash containing multiple key/values. I want to wirte all
key/value to the same row using cvs library. Is it possible to do that?
Now I follow the example from the library and I can only write each
key/value to one row and multiple rows from a hash.

Thanks,

Li

##########
EXAMPLE

Write rows to 'csvout' file.

outfile = File.open('csvout', 'wb')
CSV::Writer.generate(outfile) do |csv|
csv << ['c1', nil, '', '"', "\r\n", 'c2']

####here is my modified code###
hash.each_pair{|k,v|csv<<"#{k}","#{v}"}

...
end

outfile.close
############
 
T

Tachikoma

Hi all,

I have a hash containing multiple key/values. I want to wirte all
key/value to the same row using cvs library. Is it possible to do that?
Now I follow the example from the library and I can only write each
key/value to one row and multiple rows from a hash.

Thanks,

Li

##########
EXAMPLE

  Write rows to 'csvout' file.

  outfile = File.open('csvout', 'wb')
  CSV::Writer.generate(outfile) do |csv|
    csv << ['c1', nil, '', '"', "\r\n", 'c2']

    ####here is my modified code###
    hash.each_pair{|k,v|csv<<"#{k}","#{v}"}

    ...
  end

  outfile.close
############

I tried this:

require 'csv'
outfile = File.open('csvout','wb')
hash = {"a" => 100,"b" => 200,"c" => 300}
CSV::Writer.generate(outfile) do |csv|
csv << hash.to_a.flatten
end

the result is :
a,100,b,200,c,300

I hope this will help
 
L

Li Chen

Ikari said:
I tried this:

require 'csv'
outfile = File.open('csvout','wb')
hash = {"a" => 100,"b" => 200,"c" => 300}
CSV::Writer.generate(outfile) do |csv|
csv << hash.to_a.flatten
end

the result is :
a,100,b,200,c,300


Hi Ikari,

Thank you for your help. I also came out with the same solution:
to convert a hash into an array and so that each array will be write to
the same row in csv.


Li
 

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,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top