红宝石二维阵列:寻找一个对象的坐标 [英] Ruby two dimensional array: finding an object's coordinates
本文介绍了红宝石二维阵列:寻找一个对象的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设,我有一个二维数组 A
,它的指出,地方里面有一个对象 my_element
。什么是找出其坐标的最快方法?我使用Ruby 1.8.6。
Assume, I have a two dimensional array A
, and it's stated that somewhere inside it there's an object my_element
. What's the quickest way to find out its coordinates? I am using Ruby 1.8.6.
推荐答案
这是一种方式。我不知道这是最快的,虽然。
This is one way. I'm not sure it's the quickest, though.
class Array
def coordinates(element)
each_with_index do |subarray, i|
j = subarray.index(element)
return i, j if j
end
nil
end
end
array = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
array.coordinates(3) # => [0, 2]
array.coordinates(9) # => [2, 2]
array.coordinates(42) # => nil
这篇关于红宝石二维阵列:寻找一个对象的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文