Nuno Furtado
Nuno Furtado

Reputation: 4568

Iterating over two dimension array and knowing current position

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

visiblematrix.each do |x|
            x.each do |y|
                  puts y
            end 
end 

Upvotes: 4

Views: 13323

Answers (2)

Teoulas
Teoulas

Reputation: 2963

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

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

Upvotes: 19

Beanish
Beanish

Reputation: 1662

use each_index instead of just each.

Keep in mind x and y would now be your index not the value at that index. So visiblematrix[x] etc.

Upvotes: 8

Related Questions