0

Given this multidimensional array:

a = [ [0,'abc'], [1,'def'] ]

I want to return just the keys (where keys are index 0s of subarray) and just the values (where values are index 1s of subarray):

a.keys
# => [0,1]

a.values
# => ['abc','def']

My solution to this is to use map to return a collection and use shift and pop to return the correct items:

a.map(&:shift)
=> [0, 1] 
a.map(&:pop)
=> ["abc", "def"]

Great it works, but then I noticed the side effects:

 a
 => [[], []] 

Is there a way to get the functionality I have but without the side effects?

3
  • Not sure I understand the desired output, but Hash[a] will give you back {0 => "abc", 1 => "def"}. Is that what you're going for? Commented Jun 26, 2015 at 0:41
  • @infused my collection is an array of subarrays, not a hash. If it was a hash, it would be easy. I could just use keys and values methods. But with array there is no such keys and values method. I want all the first positions returned in one array and all the last positions returned in another array, as my example above achieves. The only problem is the side effects. Commented Jun 26, 2015 at 0:42
  • That's what converting the array to a Hash will do for you. I just posted a full answer. Commented Jun 26, 2015 at 0:45

2 Answers 2

5

First, convert your array of arrays to a Hash:

a = [ [0,'abc'], [1,'def'] ]
h = Hash[a]

Then get the keys and values:

h.keys #=> [0, 1]
h.values # => ['abc', 'def']

You can also get at the same results more directly (if the sub-arrays always have only 2 elements):

a = [ [0,'abc'], [1,'def'] ]
a.map(&:first) # => [0, 1]
a.map(&:last)  # => ['abc', 'def']
Sign up to request clarification or add additional context in comments.

Comments

3
a = [ [0,'abc'], [1,'def'] ]

k,v = a.transpose
  #=> [[0, 1], ["abc", "def"]] 
k #=> [0, 1] 
v #=> ["abc", "def"] 

I can't bring myself to write keys and values, as those words are generally reserved for hashes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.