Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array?

Tags:

arrays

ruby

Given an array:

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

Whats 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 using collect?

like image 419
Ray Dookie Avatar asked Jul 05 '10 18:07

Ray Dookie


People also ask

How do you split an array into two parts?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

Can you use split on an array?

The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it.

How do you split an array in Java?

Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.


1 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.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

like image 182
Ray Dookie Avatar answered Sep 27 '22 23:09

Ray Dookie