From: Yuh-Ruey Chen Date: 2008-11-01T04:34:00+09:00 Subject: Re: How to access to local variables in enclosing scopes? On Oct 31, 2:18 pm, Stefan Lang wrote: > 2008/10/31 Yuh-Ruey Chen : > > > > > The difference that the local variable doesn't have to be defined in > > global scope. Only child scopes should have access to that local > > variable. > > > def foo > >        a = 10 > >        def bar > >                # should somehow be able to access a > >        end > >        bar > > end > > foo > > # here, we should not be able to access foo's a, but if there is > > another a in scope, we can access that > > > Or to put it in Python: > > > a = 20 > > def foo(): > >        a = 10 > >        def bar(): > >                print a # prints 10 > >        bar() > > foo() > > print a # prints 20 > > The first assignment to a creates a _module_ scoped variable in Python. > It is _not_ local, it can very well be accessed from anywhere via > >     import some_module >     some_module.a Well then just wrap that example in another function: def scope() a = 20 def foo(): a = 10 def bar(): print a # prints 10 bar() foo() print a # prints 20 scope() My point was that scopes nest as expected. > Since it's a bad idea anyway to reassign such variables > (metaprogramming might be an exception), you can use > Ruby's constants for this purpose: > >     module MyModule > >         A = 20 > >         # can access A from anywhere within MyModule, >         # including method definitions, nested classes, etc. > >     end > >     puts MyModule::A  # access from outside of MyModule > > At least anything that looks like local variable assignment > in Ruby is actually local variable assignment. The thing to > learn is that "module", "class" and "def" create new, empty > local scopes, they have no enclosing scope with regards to > local variables. > > It is generally a better idea to genuinely try to understand > a new language and its idioms instead of bending it to ones > expectations from the beginning. > > Stefan I am trying to understand Ruby with some metaprogramming practice. But I still feel that this is a really backwards step in language design. It's like telling me I should use GOTO in original BASIC instead of trying to bend the language to simulate while loops. Would any sane modern programmer do that?