Forum: Ruby 2 dimensional array to single arrays

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0de83fd56f1af530034ba8efa5490b1b?d=identicon&s=25 John Butler (johnnybutler7)
on 2008-11-21 15:42
Hi,

I have a nasty loop which creates 2 single arrays from a 2 dimensional
array,

is there a quicker way to do it?

[["a",1],["b",2],["c",3]]

So i want an array
["a","b","c"]

and

[1,2,3]

Any quick method to do this?

JB
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2008-11-21 16:12
(Received via mailing list)
2008/11/21 John Butler <johnnybutler7@gmail.com>:
> Any quick method to do this?

letters, numbers = ["a",1],["b",2],["c",3]].transpose

Farrel
6d9fdb4fe716a92211de779a7e500821?d=identicon&s=25 Michael Tomer (michael_tomer)
on 2008-11-21 19:14
John Butler wrote:
> Hi,
>
> I have a nasty loop which creates 2 single arrays from a 2 dimensional
> array,
>
> is there a quicker way to do it?
>
> [["a",1],["b",2],["c",3]]
>
> So i want an array
> ["a","b","c"]
>
> and
>
> [1,2,3]
>
> Any quick method to do this?
>
> JB

my_array = [["a",1],["b",2],["c",3]]

letters = my_array.collect {|array| array[0]}
numbers = my_array.collect {|array| array[1]}
This topic is locked and can not be replied to.