3

假设,我有一个二维数组A,并且声明在其中某处有一个 object my_element。找出它的坐标的最快方法是什么?我正在使用 Ruby 1.8.6。

4

1 回答 1

6

这是一种方式。不过,我不确定这是最快的。

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 
于 2009-11-18T10:48:49.833 回答