# Index of an array containing an instance, from this instance

**URL:** <https://www.ruby-forum.com/t/index-of-an-array-containing-an-instance-from-this-instance/180870>\
**Category:** Ruby\
**Created:** [December 30, 2009, 11:13pm UTC](https://www.ruby-forum.com/t/index-of-an-array-containing-an-instance-from-this-instance/180870 "2009-12-30T23:13:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![judge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9de0a6/32.png) [@judge](https://www.ruby-forum.com/u/judge)\
**Post date:** [December 30, 2009, 11:13pm UTC](https://www.ruby-forum.com/t/index-of-an-array-containing-an-instance-from-this-instance/180870/1 "2009-12-30T23:13:10Z")

</div>

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?

Thanks

---

<div class="post-metadata">

**Author:** ![judge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9de0a6/32.png) [@judge](https://www.ruby-forum.com/u/judge)\
**Post date:** [December 30, 2009, 11:20pm UTC](https://www.ruby-forum.com/t/index-of-an-array-containing-an-instance-from-this-instance/180870/2 "2009-12-30T23:20:37Z")

</div>

On Dec 30, 2009, at 5:13 PM, Paul A. wrote:

> …From Foo instance, it is possible to get the array instance using  
> …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 W.

---

<div class="post-metadata">

**Author:** ![judge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9de0a6/32.png) [@judge](https://www.ruby-forum.com/u/judge)\
**Post date:** [December 30, 2009, 11:56pm UTC](https://www.ruby-forum.com/t/index-of-an-array-containing-an-instance-from-this-instance/180870/3 "2009-12-30T23:56:30Z")

</div>

Thanks for this quick answer.

Happy end’s year.
