From: Charles Comstock Date: 2004-04-15T02:09:13+09:00 Subject: Re: Interesting Scoping Rules David A. Black wrote: > Hi -- > > On Thu, 15 Apr 2004, Charles Comstock wrote: > > >>I guess I should have qualified my statement a little better, I did >>recognize that a def seems to be a hard scoping boundary, the question >>was much more that I was very suprised by this, and was curious if >>anyone had any insight as to WHY ruby chose to work things like this? > > > I think it's generally true that local variable scope changes every > time a new 'self' takes over: > > class X > # self is X > def blah > # self is any instance of X > end > # self is X again, back to where we were > end > > class X > # self is X but we've backed out of the class and > # come back in, so we have a new local scope > end > > The design is flexible: you can use #define_method instead of def, if > you want to avoid changing self and therefore starting a new local > scope. > > >>It suprises me much in the same way that we cannot def inside a def, it >>will result in a new def at the top scope. It also suprises me in the >>way that if we stick a class inside of a class instance variables will >>not bubble down into the inner class. > > > I'm not sure what you mean by that last one -- can you illustrate? > > > David > class A var = "me" class B puts var end end It's essentially the same rule that causes var = "me" class B puts var end alone not to work I suppose. The other complaint was that def a def b puts "a" end end b will result in "a" as opposed to getting a name error on b also curious is that class A @a = "me" class B puts @a end end results in nil again class appears to be a much harder scoping boundary then I expected. Or rather that class b is really class A::B and as such has no knowledge of ancestory to A. class A @a = "me" class B def t puts @a end end end A::B.new.t this is suggested by this returning nil. Charles Comstock