我正在尝试迭代一个由以下代码创建的多维数组
为了进行迭代,我使用以下代码
visiblematrix= Array.new (10) {Array.new(10){0}}
但是在迭代过程中,这种方法无法让我知道当前的x,y位置。那么如何在不使用临时变量的情况下找到它呢?
visiblematrix.each do |x|
x.each do |y|
puts y
end
end
您还可以使用Enumerable#each_with_index方法(Ruby数组包括可枚举混入)。
visiblematrix.each_with_index do |x, xi|
x.each_with_index do |y, yi|
puts "element [#{xi}, #{yi}] is #{y}"
end
end
使用each_index
代替each
。
请记住,现在的x和y将是您的索引,而不是该索引处的值。因此,可见矩阵[x]等。