How do I find .index of a multidimensional array

后端 未结 7 1654
-上瘾入骨i
-上瘾入骨i 2021-02-08 19:34

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\'         


        
7条回答
  •  再見小時候
    2021-02-08 20:12

    a.each_index { |i| j = a[i].index 'S'; p [i, j] if j }
    

    Update: OK, we can return multiple matches. It's probably best to utilize the core API as much as possible, rather than iterate one by one with interpreted Ruby code, so let's add some short-circuit exits and iterative evals to break the row into pieces. This time it's organized as an instance method on Array, and it returns an array of [row,col] subarrays.

    a = [ %w{ a b c d },
          %w{ S },
          %w{ S S S x y z },
          %w{ S S S S S S },
          %w{ x y z S },
          %w{ x y S a b },
          %w{ x },
          %w{ } ]
    
    class Array
      def locate2d test
        r = []
        each_index do |i|
          row, j0 = self[i], 0
          while row.include? test
            if j = (row.index test)
              r << [i, j0 + j]
              j  += 1
              j0 += j
              row = row.drop j
            end
          end
        end
        r
      end
    end
    
    p a.locate2d 'S'
    

提交回复
热议问题