Reputation: 1
I'm trying to find the indexes where a specific string is located in a multidimensional array in Ruby. I'm using the following code.
array = [['x', 'x',' x','x'],
['x', 'S',' ','x'],
['x', 'x','x','S']]
array.index(array.detect{|aa| aa.include?('S')}
However, this only returns 1 (the first index). Does anyone know how I can alter this command to return all the indexes where the pattern is present? This example should return 1 and 2.
Upvotes: 0
Views: 160
Reputation: 110665
One way:
array = [['x', 'x',' x','x'],
['x', 'S',' ','x'],
['x', 'x','x','S']]
array.each_with_index.with_object([]) do |(row,i),arr|
j = row.index('S')
arr << i unless j.nil?
end
#=> [1, 2]
It's only a small change to retrieve both the row and column indices (assuming there is at most one target string per row):
array.each_with_index.with_object([]) do |(row,i),arr|
j = row.index('S')
arr << [i,j] unless j.nil?
end
#=> [[1, 1], [2, 3]]
You can also use the Matrix class to obtain row/column pairs.
require 'matrix'
Matrix[*array].each_with_index.with_object([]) { |(e,i,j),arr| arr << [i,j] if e == 'S' }
#=> [[1, 1], [2, 3]]
Upvotes: 0
Reputation: 66837
Here's the updated solution now that you updated your question and added the below comment:
array.each_index.select { |i| array[i].include?('S') }
#=> [1, 2]
Upvotes: 2