Iterate over two dimensional arrays and know the current position

I am trying to iterate an array with multiple dimensions created with the following line

To continue, I use the following code

visiblematrix= Array.new (10) {Array.new(10){0}} 

But this does not allow me to know the current position of x, y during the iteration. how can I find this without resorting to temporary variables.

 visiblematrix.each do |x| x.each do |y| puts y end end 
+4
source share
2 answers

use each_index instead of each .

Keep in mind that x and y will now be your index, not the value of that index. So, the visible matrix [x], etc.

+8
source

You can also use the Enumerable # each_with_index method (ruby arrays include an enumerated mixin).

 visiblematrix.each_with_index do |x, xi| x.each_with_index do |y, yi| puts "element [#{xi}, #{yi}] is #{y}" end end 
+19
source

Source: https://habr.com/ru/post/1304878/


All Articles