How to get a specific value in an array of arrays

I have an array (external array) that contains three arrays (inside arrays), each of which has three elements.

array = [[a, b, c], [d, e, f], [g, h, i]] 

I want to select a specific internal array using the index of the external array, and then select the value inside the selected internal array based on its index. Here is what I tried:

 array.each_index{|i| puts "letter: #{array[i[3]]} " } 

I was hoping this would give me the following result

 letter: c letter: f letter: i 

but instead i get

 letter: [[a, b, c], [d, e, f], [g, h, i]] 

I also tried

 array.each_index{|i| puts "letter: #{array[i][3]} " } 

but I get the same result. Please, any suggestions are greatly appreciated. I need a simple explanation.

+4
source share
5 answers

each_index is an Enumerable that goes through all the indexes and performs an action for each of them. When this is done, he will return your original collection , as it is not his job to change it. If you want to display material using puts / print , then each_index is fine.

If you want to create a new collection as a result of going through all the elements of the original collection, you must use map ,

eg.

 array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] new_array = array.map {|el| el[2]} => ["c", "f", "i"] 

array.map iterates through the elements of the array, so at each step | el | it is an element, not an index, as in: ['a', 'b', 'c'] in the first iteration, ['d', 'e', 'f'] in the second, etc ...

Just pointing this out, as I don’t know what the purpose of what you are trying to do is.

+6
source

do it like this:

 array.each_index{|i| puts "letter: #{array[i][2]} " } 

Since you need a letter with an index of 2, not 3.

Also, the array must be defined as follows:

 array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] 
+5
source

You can use map as follows:

 a = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] a.map(&:last) # => ["c", "f", "i"] 

Or, if you really want to fit, not the collected values:

 a.each {|v| puts "letter: #{v.last}"} 

You can also use the Ruby Matrix class if you need more Matrix-y files:

 require 'matrix' m = Matrix[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] last_column = m.column_vectors.last # => Vector["c", "f", "i"] 

Now you can use any of the Vector methods on last_column , including to_a , which will return you to the familiar territory with the last column values.

+2
source

Arrays in ruby ​​are indexed from 0, not from 1. So:

 array.each_index{|i| puts "letter: #{array[i][2]} " } 

should give you what you want.

0
source

You can also try the following:

 p RUBY_VERSION arr = [[1,2,3],[4,5,6],[11,12,13]] arr.each{|x| px; x.each_index{|i| p "Digit :: #{x[i]}" if i == 2} } 

output:

 "2.0.0" [1, 2, 3] "Digit :: 3" [4, 5, 6] "Digit :: 6" [11, 12, 13] "Digit :: 13 
0
source

All Articles