Two-dimensional Ruby array: finding the coordinates of an object

Suppose I have a two-dimensional array A, and it stated that somewhere inside it there is an object my_element. What is the fastest way to find out its coordinates? I am using Ruby 1.8.6.

+3
source share
1 answer

This is one way. However, I'm not sure if this is the fastest.

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 
+6
source

Source: https://habr.com/ru/post/1723206/


All Articles