From: Robert Klemme Date: 2010-05-20T03:53:58+09:00 Subject: Re: Retrieve instance 2010/5/19 David Masover : > 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. Even with ObjectSpace you cannot really travel a reference backwards. You're merely forced to look at all objects (of a kind) and figure whether any of them references (forward) the one whose parent you are looking for as your code nicely demonstrates. Actually I find that approach so ridiculous for the case at hand that I didn't even want to come up with it. :-) > 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. Yeah, good summary of all the drawbacks of this approach. :-) > Just do what Robert Klein said. Erm, who? Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/