0

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.

2
  • A question "put on hold" has not be rejected. It simply means that you must edit the question to address the objection. If the edit is satisfactory the hold will be removed. Commented Sep 19, 2016 at 17:48
  • I nominate this question for re-opening. The edited question includes the input data, an approach that didn't work and the expected output. And frankly it already did when the last 2 close votes came in... Commented Sep 20, 2016 at 3:28

2 Answers 2

2

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] 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I edited the original because I realised that the array and subarray indexes were the same, which may be causing some confusion. So, what I want are the indexes of the subarrays containing the string. I'm not concerned with the location within each subarray. However, I get the same response when I use both your solutions, which is [nil, 1, 3]. What I"m looking for is 1,2. Hopefully that clears things up a bit. Thanks.
@kms Updated, this now does what you want.
0

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]] 

3 Comments

Don't you think that each.with_index.with_object([]) has a nice symmetry (i.e. just chaining all the Enumerable methods)? :)
@MichaelKohl, yes, though you don't show any so far... :-)
Ugh, I wrote Enumerable again when I meant Enumerator. One day I'll get this right... ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.