How to split an array?

Given an array:

arr = [['a', '1'], ['b','2'], ['c', '3']] 

What is the best way to split it into two arrays?

For example, from the array above I want to get the following two arrays:

first = ['a','b','c']  
second = ['1', '2', '3'] 

Can I do this with help collect?

+5
source share
4 answers

ok I just stumbled upon arr.transpose

arr = [['a', '1'], ['b','2'], ['c', '3']].transpose 

first = arr[0] 

second = arr[1] 

compared to the answers above arr.zip, arr.mapand foreachwhich is more efficient? Or is this the most elegant solution?

OR (Thanks, comment by Jörg W Mittag - see Comment below) first, second = arr.transpose

+15
source

Using the method is zipalso pretty elegant:

arr[0].zip *arr[1..-1]
first = arr[0]
second = arr[1]
+4
source
arr = [['a', '1'], ['b','2'], ['c', '3']]

a = []
b = []

arr.each{ |i| a << i[0]; b << i[1] }
+1

collect ( ), , map/collect .

first = arr.map { |element| element[0] }   
second = arr.map { |element| element[1] }

which has the disadvantage of repeating an iteration over arr twice. However, this usually should not be a problem if you are not dealing with a large number of elements or this operation must be performed many times.

0
source

All Articles