From: Logan Capaldo Date: 2006-08-01T04:23:27+09:00 Subject: Re: I thought this was the one that worked? On Jul 31, 2006, at 2:49 PM, Eric Armstrong wrote: > #!/usr/bin/env ruby > > repeat = 1 > > def run > number_of_times = repeat > number_of_times.downto(0) do > puts number_of_times > sleep 1 > end > end > > run > ---------------------------- > > Fails: undefined variable, "repeat" > in first line of run method > > I would have sworn that this was the > one that worked. I know that for a class > definition, the value of "repeat" isn't > known in an instance. That makes sense > to me (now). > > But here, I'm in a script. I am continually > surprised by this behavior. In my mental > model, the run method is a "subsidiary" > context of the larger context, and as such > it should just "naturally" be aware of values > defined in the wider context. > > Obviously, my mental model is way, way off, > which is why I keep getting surprised. Can > anyone enlighten me? > > thanks > eric > > > repeat is a local variable. class, def, and module introduce a new scope without closing over their enclosing scope. Blocks introduce a new scope that does enclose it's enclosing scope. repeat = 1 # local variable repeat def run # I just introduced a new scope. I can't see local variables outside my body define_method("run") { # I just introduced a new scope, but I'm also a closure, I can see repeat. Note that this issue has nothing to do with instances vs. classes, etc.