views:

40

answers:

2

Hello,

Is there a simple way, instead of looping my entire array to fetch the first value of every inner array.

so in essence I have the following;

array = [['test', 'test2'...], ['test' ....]]

so I want to grab array[#][0] and store the unqiue values.

EDIT

Is there a similar way to use the transpose method for arrays with Hash?

I essentially want to do the same thing Hash = {1=> {1=> 'test', .....}, 2=> {1=> 'test',....}

so at the end I want to have something like new hash variable and leave my existing hash within hash alone.... = {1 => 'test', 2=> 'test2'}

+2  A: 

Not sure if I fully understand the question, but if you have a 2 dimensional array (array in array), and you want to turn that into an array of the first element of the second dimension, you can use the map function

firsts = array.map {|array2| array2.first}

The way map works is that it turns one collection into a second collection by applying a function you provide (the block) to each element.

Matt Briggs
Chubas
Yeah, I didn't really feel like explaining Symbol#to_proc though
Matt Briggs
+2  A: 

Maybe this?

array.transpose[0]
Dave
This would be my best guess as well, but will only work if the array contains arrays of equal size
William
Yes, the arrays will always be equal size, let me try this out; I knew there was a method that basically did this already, juts couldnt find it at the top of my head :)
Actually is there a similar way to do this with Hashes instead Hashes?