开发者

Ruby two dimensional array: finding an object's coordinates

开发者 https://www.devze.com 2022-12-12 07:17 出处:网络
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 o开发者_如何学Pythonut its coordinates? I am using R

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 o开发者_如何学Pythonut 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 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号