From: "David A. Black" Date: 2008-11-01T02:55:11+09:00 Subject: Re: How to access to local variables in enclosing scopes? Hi -- On Sat, 1 Nov 2008, Yuh-Ruey Chen wrote: > I'm familiar with other popular scripting languages (JS and Python), > and I'm struggling to figure out Ruby's (inanely) complex scoping > mechanisms. The rules are pretty simple. The def, class, and module keywords start new local scopes. That's most of it. > My questions are within the following example: > > x = 10 > > def foo > # how to access x from here? > > end > > class Klass > # how to access x from here? > def bar > # how to access x from here? > end > end > > lambda { x } # I can access x here but why not in foo or Klass or bar? I'm not sure what you mean by "why". Every language has scoping rules. Ruby's rules include provision for closures, in that code blocks do not start a new local scope and can be used as the bodies of anonymous function objects. There's no moral imperative, one way or the other. You're just encountering and learning how Ruby handles these things. Relax :-) > I sincerely hope I'm missing something here. To me, the inability to > access local variables in an enclosing scope is very counter- > intuitive. I thought Ruby was supposed to be elegant? At the very > least, I expect some sort of "nonlocal" statement similar to Python, > e.g. > > def foo > nonlocal x > # I can access x in enclosing scope now > end I thought you said you wanted elegance :-) > And no, I don't want to have to use global variables - that would just > be pollution and would be incredibly unwieldy in large projects. > Frankly, if there was a way to access local variables in enclosing > scopes, there wouldn't even need to be a special global variable > concept. Have you looked at class_eval and define_method? class MyClass; end m = "my_method" MyClass.class_eval do define_method(m) { puts "Hi from #{m}!" } end and similar. David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!