Write multiple key/value to a row using cvs library

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
############

Ikari S. wrote:

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

On Jul 16, 10:56 pm, Li Chen [email protected] wrote:

hash.each_pair{|k,v|csv<<"#{k}","#{v}"}

...

end

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

Posted viahttp://www.ruby-forum.com/.

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs