From: Lyle Johnson Date: 2003-01-24T08:45:37+09:00 Subject: Re: contained_by method (challange) Tom Sawyer wrote: > okay, after all this time i finally figured out exactly what i am after. Congratulations; so few people reach that point in their life ;) > i would like all my objects to have a #contained_by method that returns a > reference to the object they are contained by. > > for example: > > a = "1" > ar = [a] > a.contained_by # --> reference to ar > > another: > > class T > attr_reader :a > end > t = T.new > t.a.contained_by # --> reference to t > > and so on. > > is this possible? For starters, you need to clarify what you mean by an object "containing" another object. For your first example, you're talking about one object that is a member of an Array. For your second example, you're talking about an object that is an instance variable of another object. Those are two different concepts. If you just wanted to focus on the first case -- a method that returns a list of all the arrays that include the object as an array member -- you could use this: class Object # Return an array of the arrays that contain me def contained_by containers = [] ObjectSpace.each_object(Array) { |anArray| containers << anArray if anArray.include? self } containers end end Hope this helps, Lyle