尝试过网络资源,但没有任何运气和我的视觉快速入门指南.
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然后我去输入:
array = ['x', 'S',' ','x'] print array.index('S')它返回我正在寻找的值 1
it returns the value I am looking for 1
我的第一个猜测是 .index() 中的某些东西被称为错误,它需要两个参数分别用于行和列?无论如何,我如何让 .index 为多维数组工作?这是解决我的小迷宫问题的第一步
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
推荐答案 a.each_index { |i| j = a[i].index 'S'; p [i, j] if j }更新:好的,我们可以返回多个匹配项.最好尽可能多地利用核心 API,而不是用解释过的 Ruby 代码一一迭代,所以让我们添加一些短路退出和迭代 eval 来将行分成几部分.这次它被组织成 Array 上的一个实例方法,它返回一个 [row,col] 子数组的数组.
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'更多推荐
如何找到多维数组的 .index
发布评论