Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find .index of a multidimensional array

Tags:

ruby

Tried web resources and didnt have any luck and my visual quick start guide.

If I have my 2d/multidimensional array:

 array = [['x', 'x',' x','x'],
         ['x', 'S',' ','x'],
         ['x', 'x',' x','x']]

   print array.index('S')

   it returns nil

So then I go and type:

 array = ['x', 'S',' ','x']
 print array.index('S')

it returns the value I am looking for 1

My first guess something is being called wrong in the .index() and it needs two arguments one for both row and column? Anyways how do I make .index work for a multidimensional array? This is step one for solving my little maze problem

like image 559
Matt Avatar asked Dec 05 '09 01:12

Matt


People also ask

How do get the size of 2nd row in a two-dimensional array?

We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.

How do you find the total number of elements in a multidimensional array?

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

How do you find the index of a 2D array?

map(function(row) { return stringle(row); }); Then you can use Array. indexOf() (or other array methods) to check for the presence or location of matches.

How do you find indices from an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.


1 Answers

This will do it:

array = [['x', 'x',' x','x'],
         ['x', 'S',' ','x'],
         ['x', 'x',' x','x']]

p array.index(array.detect{|aa| aa.include?('S')}) # prints 1

If you also want 'S's index in the sub array you could:

row = array.detect{|aa| aa.include?('S')}
p [row.index('S'), array.index(row)] # prints [1,1]
like image 173
samg Avatar answered Oct 14 '22 23:10

samg