Given an array arr = [['a', '1'], ['b','2'], ['c', '3']]
Whats the best way to split it into 2 arrays
eg:
first = ['a','b','c'] and
second = ['1', '2', '3'] ..can i do this via a collect?
Given an array arr = [['a', '1'], ['b','2'], ['c', '3']]
Whats the best way to split it into 2 arrays
eg:
first = ['a','b','c'] and
second = ['1', '2', '3'] ..can i do this via a collect?
arr = [['a', '1'], ['b','2'], ['c', '3']]
a = []
b = []
arr.each{ |i| a << i[0]; b << i[1] }
You can do this via collect (an alias of map), but not in a single operation, because map/collect always returns a single Array. You could do
first = arr.map { |element| element[0] }
second = arr.map { |element| element[1] }
which has the disadvantage of iterating over arr twice. However, that shouldn't normally be a problem, unless you are dealing with a large amount of elements or this operation has to run a large number of times.
Using the zip
method is quite elegant as well:
arr[0].zip *arr[1..-1]
first = arr[0]
second = arr[1]
ok i just stumbled upon arr.traspose
arr = [['a', '1'], ['b','2'], ['c', '3']].transpose
first = arr[0]
second = arr[1]
compared to the answers above arr.zip, arr.map, and the foreach, which is more efficient? Or which is the most elegant solution?
OR (Thanks to comment by Jörg W Mittag - see comment below) first, second = arr.transpose