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
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.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With