From: Gary Wright Date: 2009-12-31T07:19:20+09:00 Subject: Re: Index of an array containing an instance, from this instance On Dec 30, 2009, at 5:13 PM, Paul A. wrote: > Hi, > > If I do this: > > class Foo > end > > my_array = [] > my_array[8] = Foo.new > > ...From Foo instance, it is possible to get the array instance using > self, such with: > > Class Foo > def test > puts "the array is: #{self}" > end > end > > my_array[8].test # => the array is: (something like fooooobaaaar) > > ...But is that possible to get its current indice (which is 8) where Foo > is stored? In other words, how can I get the current indice of the array > from Foo instance? An object doesn't have any built-in notion of what other objects are referencing it. In your example the array would have a reference to the Foo instance but the Foo instance doesn't automatically have any reverse reference to the array. If you want/need that sort of thing you'll have to incorporate it into your implementation of Foo. It is possible to search an array for a particular object and to return the index: class Foo end my_array = [] instance = Foo.new my_array[8] = instance puts "index: #{my_array.index(instance)}" # 8 Gary Wright