# Column to line

**URL:** <https://www.ruby-forum.com/t/column-to-line/138160>\
**Category:** Rails\
**Created:** [May 20, 2008, 5:51pm UTC](https://www.ruby-forum.com/t/column-to-line/138160 "2008-05-20T17:51:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jef](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e5b9ba/32.png) [@jef](https://www.ruby-forum.com/u/jef)\
**Post date:** [May 20, 2008, 5:51pm UTC](https://www.ruby-forum.com/t/column-to-line/138160/1 "2008-05-20T17:51:31Z")

</div>

Hi,

I’ve got a hash:

{:colA=\>[“blue”,“red”,“green”], :colB=\>[“diesel”,“fuel cell”,“gas”],  
colC=\>[“bus”,“truck”,“car”]}

All arrays are the same size.

I would like to turn it into a array of line , and get this

[  
[“blue”,“diesel”,“bus”],  
[“red”,“fuel cell”,“truck”],  
[“green”,“gas”,“car”]  
]

What is the best way to do this?

Thanks

---

<div class="post-metadata">

**Author:** ![jef](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e5b9ba/32.png) [@jef](https://www.ruby-forum.com/u/jef)\
**Post date:** [May 20, 2008, 6:09pm UTC](https://www.ruby-forum.com/t/column-to-line/138160/2 "2008-05-20T18:09:13Z")

</div>

> [“blue”,“diesel”,“bus”],  
> [“red”,“fuel cell”,“truck”],  
> [“green”,“gas”,“car”]  
> ]
> 
> What is the best way to do this?

No idea if it’s the best…

irb\> h = {:colA=\>[“blue”,“red”,“green”],  
:colB=\>[“diesel”,“fuel cell”,“gas”], :colC=\>[“bus”,“truck”,“car”]}

irb\> (0…2).map {|i| [h[:colA][i], h[:colB][i], h[:colC][i]]}

=\> [[“blue”, “diesel”, “bus”], [“red”, “fuel cell”, “truck”],  
[“green”, “gas”, “car”]]

---

<div class="post-metadata">

**Author:** ![jef](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e5b9ba/32.png) [@jef](https://www.ruby-forum.com/u/jef)\
**Post date:** [May 20, 2008, 6:34pm UTC](https://www.ruby-forum.com/t/column-to-line/138160/3 "2008-05-20T18:34:29Z")

</div>

On Tue, May 20, 2008 at 08:51:01AM -0700, jef wrote:

> I would like to turn it into a array of line , and get this
> 
> [  
> [“blue”,“diesel”,“bus”],  
> [“red”,“fuel cell”,“truck”],  
> [“green”,“gas”,“car”]  
> ]
> 
> What is the best way to do this?

There are two pieces here. One is turning it into an arrays of arrays,  
the  
other is transposing. If the order matters, use this to get the array of  
arrays:

arr = [:colA, :colB, :colC].map { |k| hash[k] }

…otherwise:

arr = hash.values

Once you have an array of arrays, there is already a transpose method:

arr = arr.transpose

> Thanks  
> –Greg
