From: David Alan Black Date: 2002-07-05T08:45:06+09:00 Subject: Re: self_parent Hi -- On Fri, 5 Jul 2002, Tom Sawyer wrote: > class Customer > attr_reader :name, :address > def initialize(name, address) > @name = name > @address = Address.new(address) > end > def pretty_name > return @name.upcase > end > end > > class Address > def initialize(address) > @address = address > end > def print_label > puts self_parent.pretty_name > puts @address > end > end > > c = Customer.new("John Doe", "111 Test Ln.\n Santa Fe, NM 87501") > c.address.print_label This introduces a dependency between objects, though, based on a kind of "self" stack, which won't necessarily mesh with the actual design and behavior of the classes and objects. For example, let's say you wanted to refactor/rewrite Customer like this: class Factory def Factory.make(thing,*args) const_get(thing).new(*args) end end class Customer def initialize(name, address) @name = name @address = Factory.make("Address", address) end ... end Not a very elegant example -- but the point is, now you're two "self"s away, instead of one, but your Address objects are hardcoded to look one "self" away. I know Ruby allows for a lot of introspection... but I think relying on this would constrain code and code growth significantly. > no need to pass self and explicitly store it. so there's a fictional > example for you. in the real world there are many cases of such a > parent-child relationship. in fact i think REXML has an explicit Parent > class it uses to glue such realtionships together. hiearchy structures > too (like a tree) are another area in which a parent-child relationships > of this sort are used. and i'm sure there are many others. REXML is specifically modeling the parent/child relationships of XML in that class, though (I think). That's different from a language-level (I mean Ruby, not XML) description of one object as the "parent" of another because the second object is created by a method of the first object. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav