I am trying to iterate a multidimension array created with the following line
我试图迭代使用以下行创建的多维数组
To iterate i'm using the following code
迭代我使用以下代码
visiblematrix= Array.new (10) {Array.new(10){0}}
But this doesn't allow me to know the current x,y position while iterating. how can i find it out without resorting to temporary variables
但这不允许我在迭代时知道当前的x,y位置。如何在不诉诸临时变量的情况下找到它
visiblematrix.each do |x|
x.each do |y|
puts y
end
end
2 个解决方案
#1
8
use each_index
instead of just each
.
使用each_index而不是每个。
Keep in mind x and y would now be your index not the value at that index. So visiblematrix[x] etc.
请记住,x和y现在将是您的索引,而不是该索引处的值。所以visiblematrix [x]等
#2
19
You can also use the Enumerable#each_with_index method (ruby arrays include the Enumerable mixin).
您还可以使用Enumerable#each_with_index方法(ruby数组包含Enumerable mixin)。
visiblematrix.each_with_index do |x, xi|
x.each_with_index do |y, yi|
puts "element [#{xi}, #{yi}] is #{y}"
end
end
#1
8
use each_index
instead of just each
.
使用each_index而不是每个。
Keep in mind x and y would now be your index not the value at that index. So visiblematrix[x] etc.
请记住,x和y现在将是您的索引,而不是该索引处的值。所以visiblematrix [x]等
#2
19
You can also use the Enumerable#each_with_index method (ruby arrays include the Enumerable mixin).
您还可以使用Enumerable#each_with_index方法(ruby数组包含Enumerable mixin)。
visiblematrix.each_with_index do |x, xi|
x.each_with_index do |y, yi|
puts "element [#{xi}, #{yi}] is #{y}"
end
end