From: David Masover Date: 2010-05-20T01:08:00+09:00 Subject: Re: Retrieve instance On Wednesday, May 19, 2010 09:54:03 am Robert Klemme wrote: > 2010/5/19 Walle Wallen : > > Quick question. Can I somehow retrieve the instance of the class Test in > > which the variable con exists. As in the example below, can I retrieve > > the instance of Test from the variable p? > > There is no general mechanism that would allow to follow an object > reference backwards. If there was, that mechanism would yield > multiple instances because a object can be referenced by any number of > other objects. Well, there's ObjectSpace. Probably not general (cross-interpreter), but it does work if you actually need this functionality. However, ObjectSpace is code smell -- if you're using ObjectSpace, either you _really_ know what you're doing, or you probably need to rethink your design. If you do need that, for some reason: def find_con con ObjectSpace.each_object(Test).select{|t| t.con == con} end Of course, that assumes you want to test for equality. If you want to make sure they're actually the same object, you might do def find_con con ObjectSpace.each_object(Test).select{|t| t.con.object_id == con.object_id} end And of course, that will return an array. It will also not be particularly fast, and it won't necessarily be reliable -- for example, if you don't have a reference to the Test object anymore, it might be garbage collected before you go looking for it, but it might not -- so there's all sorts of possibilities for subtle bugs that only show up sometimes. Just do what Robert Klein said.