在多维数组中查找多个索引

时间:2016-09-19 03:42:24

标签: arrays ruby

我正在尝试在Ruby中找到特定字符串位于多维数组中的索引。我正在使用以下代码。

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

array.index(array.detect{|aa| aa.include?('S')}

但是,这只返回1(第一个索引)。有谁知道如何更改此命令以返回模式所在的所有索引?此示例应返回1和2.

2 个答案:

答案 0 :(得分:2)

此处有更新的解决方案,您现在更新了问题并添加了以下注释:

array.each_index.select { |i| array[i].include?('S') }
#=> [1, 2]

答案 1 :(得分:0)

一种方式:

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]

检索行索引和列索引只是一个很小的改动(假设每行最多有一个目标字符串):

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

您还可以使用Matrix类来获取行/列对。

require 'matrix'

Matrix[*array].each_with_index.with_object([]) { |(e,i,j),arr| arr << [i,j] if e == 'S' }
  #=> [[1, 1], [2, 3]] 
相关问题