Column to line

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

[“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”]]

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

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