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" Array
s):
["value1", "value2", "value3"]
How can I make that in a smart way?
The simple code to search the value in multidimensional array is described as follows: array_search($value['id'], array_column($studentsAddress, 'user_id'))
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][:] .
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];
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.
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".
>> 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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With