Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
write multiple key/value to a row using cvs library
Li Chen
7/16/2008 2:57:00 PM
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
############
--
Posted via
http://www.ruby-...
.
2 Answers
Tachikoma
7/17/2008 2:35:00 AM
0
On Jul 16, 10:56 pm, Li Chen <chen_...@yahoo.com> wrote:
> 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
> ############
> --
> Posted via
http://www.ruby-...
.
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
Li Chen
7/17/2008 1:39:00 PM
0
Ikari Shinji 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
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
write multiple key/value to a row using cvs library
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password