I should also really make myself read long blocks of text to avoiding longer 
blocks of text.

Da Streda 08 Februr 2006 05:57 Dave Cantrell napsal:
> In both the Ruby example and the pseudo-code case,
> the variable foo is a globally-scoped variable (well, for that code
> snippet anyway) and therefore should be accessible to any function that
> is subordinate to it.

There's a new term, subordinate functions. But this is essentially the bit 
where you blooped up, foo isn't globally scoped. Not even in that code 
snippet. Method definitions aren't a closure on their enclosing lexical scope 
- they run in a separate scope.

>    class MethodList
>      def initialize
>        @methods = []
>      end
>
>      def add(&block)
>        @methods << block
>      end
>
>      def run(param)
>        i = param
>        @methods.each { |m| i = m.call(i) }
>        i
>      end
>    end
>
>    m = MethodList.new
>    m.add { |x| x + 1 }
>    m.add { |x| x + 1 }
>    m.add { |x| x + 1 }
>
>    puts m.run(1)
>

Arguably a better example of shared lexical closure than mine, but I didn't 
feel like hacking up classes. If you can understand why i is four, then 
indeed you've pretty much gotten the hang of all there is to it about how 
blocks and closures work.

Hmm, I might even rip off your example as a simple stupefactor for people that 
don't know Ruby to go along with my "open Integer and then define a 
linear-time factorial with Enumerable#inject" one.

David Vallner