On 2/28/06, Yukihiro Matsumoto <matz / ruby-lang.org> wrote:
> Yes, and in Ruby2.0, this will be changed to "if you see an assignment
> to a bare name, that name means a variable in the current scope", so
> that
>
> | def foo
> |   n # method
> | end
> |
> | def bar
> |   n = 3
> |   n # variable
> | end
> |
> | def baz
> |   n # will be variable
> |   n = 3
> |   n # variable
> | end

So, then, what will you do with this:

def foo
   bar %(
      bar=1
   )
end

Should the first bar be a variable or method? If you assume it's a
method initially, the rest looks like a string, and there's no
apparent assignment in the rest of the method to clue the parser in
that it needs to go back and make it a variable instead. Granted, this
example is pathological, but I think there might be less pathological
cases that have the same problem.

I think that the current rule that local variables are declared on
first assignment is a good one. Yes, it leads to confusion in a few
cases, mostly for those who aren't aware that this is one of ruby's
few gotchas. But Ruby is hard enough to parse now; I need to look an
arbitrary number of tokens into the past to determine if a name is a
local var or not. I'd rather not have to look an arbitrary number of
tokens into the future(!) as well. Especially as there seems to be
little need for this new feature. (Unassigned locals will (presumably)
always be nil before the first assignment anyway; why would you want
to use a variable before its first (lexical) assignment? Your example
with the local variable in a block didn't seem to address that
question.)

If you are going to make this change, I (and others trying to write
ruby parsers) would appreciate an explanation of exactly when a local
variable can be back-declared, and how to handle pathological cases
like I gave above.