# Write multiple key/value to a row using cvs library

**URL:** <https://www.ruby-forum.com/t/write-multiple-key-value-to-a-row-using-cvs-library/143233>\
**Category:** Ruby\
**Created:** [July 16, 2008, 5:01pm UTC](https://www.ruby-forum.com/t/write-multiple-key-value-to-a-row-using-cvs-library/143233 "2008-07-16T17:01:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [July 16, 2008, 5:01pm UTC](https://www.ruby-forum.com/t/write-multiple-key-value-to-a-row-using-cvs-library/143233/1 "2008-07-16T17:01:16Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [July 17, 2008, 3:43pm UTC](https://www.ruby-forum.com/t/write-multiple-key-value-to-a-row-using-cvs-library/143233/2 "2008-07-17T15:43:44Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alex-osu3](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/13edae/32.png) [@alex-osu3](https://www.ruby-forum.com/u/alex-osu3)\
**Post date:** [July 17, 2008, 4:36am UTC](https://www.ruby-forum.com/t/write-multiple-key-value-to-a-row-using-cvs-library/143233/3 "2008-07-17T04:36:01Z")

</div>

On Jul 16, 10:56 pm, Li Chen [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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
