Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "extract" values from a multidimensional array in a smart way?

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?

like image 410
user12882 Avatar asked Jun 26 '12 09:06

user12882


People also ask

How do you find the value of multidimensional array?

The simple code to search the value in multidimensional array is described as follows: array_search($value['id'], array_column($studentsAddress, 'user_id'))

How do you extract a row from a multi-dimensional array?

Your multi-dimensional array is just an array of arrays, so, for example, the third row is Grille[2] is an array of six items, [0,0,0,0,0,0] . If you want a copy of the whole row, use something like row = Grille[2][:] .

How do you read multidimensional arrays?

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. The general form of declaring N-dimensional arrays is: data_type array_name[size1][size2]....[sizeN];

How do you handle multidimensional arrays?

You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.


2 Answers

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

like image 183
sohaibbbhatti Avatar answered Sep 21 '22 17:09

sohaibbbhatti


>> 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"]
like image 21
Waseem Avatar answered Sep 22 '22 17:09

Waseem