>> Keep in mind that you are looking at just one side of the coin. There's
>> a flip side to it. Preventing local variables from willy-nilly
>> infecting your methods is a Good Thing, and is usually what you want.
> 
> I agree, it's a good thing.

Here you agree, but earlier in the same post you disagree:

Yuh-Ruey Chen wrote:
> I've also noticed that there is a break in symmetry between |def| and |
> define_method| besides this block issue. Compare:

The break in symmetry is intentional because it prevents local variables 
from willy-nilly infecting your methods, which you agreed is a good 
thing.

> 
> These would be functionally equivalent if there were some way,
> analagous to the former's |self.x|, to access vars in enclosing
> scopes. I'd argue that such a symmetry would be elegant.
> 
> 
> x = 10
> def foo
>   x # accessed outside x
> end
> 
> wouldn't be a good thing, because adding a new method called "x" would
> ruin it.
> 
> But something like:
> 
> x = 10
> def foo
>   scope.x
> end
> 
> would not be as fragile, assuming |scope| is a new builtin method that
> does what you'd expect it do.
> 

But then you've missed out on the advantage of lexical local variables. 
What you propose takes the "lexical" out of "lexical scope".  It is just 
nested variables which are visible from other scopes.

If that is what you wish, then you do not mean local (lexical) 
variables.  You mean shared data, and Ruby wants you to be explicit 
about when you want shared data that will "infect" your method and class 
definitions.  This is a good thing.

require 'ostruct'

module Top
  SHARED = OpenStruct.new
  SHARED.x = 10

  class Foo
    def bar
      p SHARED.x
    end
  end
end

Top::Foo.new.bar  #=> 10

Lexical variables are used when you most definitely DO NOT want that. 
It is useful to have this distinction, because with lexicals you are 
guaranteed that no such infection can occur.  (Unless you explicitly 
want it via define_method.)

>> class Klass
>>  GLOBALS.x
>>  def bar
>>   GLOBALS.x
>>  end
>> end
>>
>> This makes your intention explicit. If you know python, you've probably
>> heard the phrase, "Explicit is better than implicit." :)
> 
> Except I do NOT want x to be globally accessible. I just want to to be
> accessible be child scopes. If I wanted it to be globally accessible,
> then I would just use global variables.

So don't make it global, as in the Top example above.

-- 
Posted via http://www.ruby-forum.com/.