views:

180

answers:

5

I've got a multidimensional array:

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

Now I need to ruturn the "coordinates" of "f", which should be (1,2). How can I do this without knowing which "row" "f" is in? I've been trying to use the index method, but this only works when I tell it where to look, i.e.

foo[1].index("f")  #=>2

I tried something like

foo[0..2][0..2].index("f")

but that just returns nil.

Is this possible?

+1  A: 

You would probably need to loop through the arrays to find the letter, then print out the location.

This is more of a general code snippet not actual ruby. But the concept is there. Don't know if there is a better way though.

for(int i = 0; i < 3; i++ ) {
 for(int x = 0; i < 3; x++ ) {
  if( foo[i][x] == 'f' ) {
   print x, i;
  }
 }
}
Suroot
A: 

You can use

foo.flatten

To get a flattened array, and then use index

DasBoot
+3  A: 
foo.each_with_index do |item, index|
  if item.index('f')
    // the array number that 'f' is in
    puts "Array number: #{index}"
    // the index in that array of the letter 'f'
    puts item.index('f')
  end
end
marktucks
+4  A: 

Loop through the array's indexes and return the current path when you find what you want. Here's an example method:

def find2d(array, elem)
  array.each_with_index do |row, row_idx|
    row.each_with_index do |col, col_idx|
      return [row_idx, col_idx] if col == elem
    end
  end
end
Chuck
+1  A: 

Another way, just for amusement:

y = nil
x = (0...foo.size).find {|xi| y = foo[xi].index("f")}

The "y=nil" part just defines "y" before the loop so you can read it afterwards...

glenn mcdonald