14

I am using Ruby on Rails 3.2.2 and Ruby 1.9.2.

Given the following multidimensional Array:

[["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]

I would like to get (note: I would like to "extract" only the first value of all "nested" Arrays):

["value1", "value2", "value3"]

How can I make that in a smart way?

user12882
  • 4,702
  • 9
  • 39
  • 54
  • 1
    possible duplicate of [Given an Array A of n subArrays Sn, how can I select the Array of Sn\[i\] members in Ruby?](http://stackoverflow.com/questions/11120244/given-an-array-a-of-n-subarrays-sn-how-can-i-select-the-array-of-sni-members) – KL-7 Jun 26 '12 at 09:24
  • @KL-7 - You are right, but I didn't find the question you linked before to post a new one. – user12882 Jun 26 '12 at 09:33

3 Answers3

29

You can use Array#collect to execute a block for each element of the outer array. To get the first element, pass a block that indexes the array.

arr.collect {|ind| ind[0]}

In use:

arr = [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]
=> [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]
arr.collect {|ind| ind[0]}
=> ["value1", "value2", "value3"]

Instead of {|ind| ind[0]}, you can use Array#first to get the first element of each inner array:

arr.collect(&:first)

For the &:first syntax, read "Ruby/Ruby on Rails ampersand colon shortcut".

Community
  • 1
  • 1
sohaibbbhatti
  • 2,672
  • 22
  • 21
2
>> array = [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]
=> [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]
>> array.map { |v| v[0] }
=> ["value1", "value2", "value3"]
Waseem
  • 8,232
  • 9
  • 43
  • 54
  • For clarification, there is no difference between `arr.map` and `arr.collect`. See http://stackoverflow.com/questions/5254732/difference-between-map-and-collect-in-ruby – forforf Jul 10 '16 at 22:06
1
arr = [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]

Solution1 = arr.map {|elem| elem.first}

Solution2 = arr.transpose[0]
NEHAL AMIN
  • 121
  • 5