On Jul 31, 2006, at 11:41 PM, Eric Armstrong wrote:

>> On Jul 31, 2006, at 2:49 PM, Eric Armstrong wrote:
>>> #!/usr/bin/env ruby
>>>
>>> repeat = 1
>>>
>>> def run
>>>   number_of_times = repeat
>>>   ...
>>> Fails: undefined variable, "repeat"
>>>        in first line of run method
>>>
>>> I would have sworn that this was the
>>> one that worked.
>>>
> I swear to the heavens that it was an innocent question?
> (But I look forward to a clear differentiation
> between closures and blocks from the thread that
> resulted.)
>
>
>> class, **def**, and module introduce a new scope without closing  
>> over their enclosing scope.
> >
> That was the shift I needed in my mental model.
> Thanks much. I expected that behavior from class
> and module. I am quite surprised that it is true
> for def, as well.
>
> That surprise leads me to ask: Why?
> What is it that made that a good idea?
>
> thanks, all
> eric
>
>

I imagine it was to avoid having to declare local variables. e.g.:

a = 1

def add_two
   a = 2
   return a + n
end


... hundred of lines of code later ...

def b
   puts a
end

Now I imagine when our hypothetical programmer wrote b he expected it  
to always print the value of the top-level a.

OTOH when he wrote add_two he was expecting a to behave as a local  
variable.

If defs were closures, we'd have to write

def foo
   my a
   or
   local a
   or
   declare a
   or
   var a
end

etc. to make sure we weren't in in-advertantly using an effectively  
"global" variable