Ruby two dimensional array: finding an object'

2019-04-12 10:56发布

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.

1条回答
做个烂人
2楼-- · 2019-04-12 11:44

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 
查看更多
登录 后发表回答