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.
views:
216answers:
1
+4
A:
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
mtyaka
2009-11-18 10:48:49
Elegant implentation of the coordinates method but I wouldn't add it into the Array class because it doesn't really apply to all arrays. Similar to the argument about whether a "sum" method should be added to Array.
mikej
2009-11-18 12:18:15
@mikej Yup, totally agree. I added it into the Array class for demonstration purposes only.
mtyaka
2009-11-18 15:08:30
Well, as I thought. Anyway, thanks!
gmile
2009-11-18 21:17:16