Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get specific value within an array of arrays

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

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

I want to select the specific inside array using an index of the outside array and then select the value within the selected inside array based off its index. Here is what I tried:

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

I was hoping that would give me the following output

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 very appreciated. I need a simple explanation.

like image 831
kingweaver88 Avatar asked Dec 04 '22 11:12

kingweaver88


1 Answers

each_index is an Enumerable which goes through all indices and performs an action on each one. When it's done it will return your original collection as it's not its job to change it. If you want to output stuff on the screen via 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 an original collection, you should use map.

e.g.

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

array.map iterates through array's elements so in every step |el| is an element, not an index, as in: ['a', 'b', 'c'] in the first iteration, ['d', 'e', 'f'] in the second one and so on...

Just pointing this out since I don't know what's the goal of what you're trying to do.

like image 175
ellmo Avatar answered Dec 15 '22 00:12

ellmo