尝试了网络资源,但没有任何运气和我的可视化快速入门指南。
如果我有二维/多维数组:
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
我的第一个猜测是在 .index() 中调用错误,它需要两个参数,一个用于行和列?无论如何,如何使 .index 为多维数组工作?这是解决我的小迷宫问题的第一步
最佳答案
这样做就可以了:
array = [['x', 'x',' x','x'],
['x', 'S',' ','x'],
['x', 'x',' x','x']]
p array.index(array.detect{|aa| aa.include?('S')}) # prints 1
如果您还想在子数组中使用 'S' 索引,您可以:
row = array.detect{|aa| aa.include?('S')}
p [row.index('S'), array.index(row)] # prints [1,1]
关于ruby - 如何找到多维数组的 .index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1850756/