Da Streda 08 Februr 2006 05:57 Dave Cantrell napsal:
> > Contrast this to Ruby:
> >
> > 	def do_yield()
> > 		yield
> > 	end
> >
> > 	foo = "FOO"
> > 	do_yield() {
> > 		foo = "BAR"
> > 	}
> > 	puts foo # Outputs "BAR".
> >
> > Which means you can assign to local variables in the closure's lexical
> > scope from inside the closure.
>
> Question: How is the above different from, say in pseudo code:
>
>    function do_something(in)
>      foo = in
>    end function
>
>    foo = "FOO"
>    do_something("BAR")
>
>    print foo  # should still output "BAR", right?
>

Wrong. Presuming the pseudocode behaves like ruby with respect to scoping 
rules, the "foo = in" in #do_something creates a new local variable foo and 
assigns "BAR" to it. 

You can of course share a global variable, in Ruby: $foo. The difference with 
using a closure is that you share a -local- variable from the enclosing 
scope. For a (very contrived) example of where the difference shows:

	def do_yield
		yield
	end

	foo = "FOO" # Local variable in the toplevel scope.

	def change_and_print_a_foo # *Groan*
		# A new local variable in the scope of the method. The toplevel 
		# variable of the same name cannot be accessed here.
		foo = "BAR"
		puts foo # Outputs BAR.

		do_yield {
			foo = "QUUX"
		}

		puts foo # Outputs QUUX.
	end

	change_and_print_a_foo

	puts foo # Outputs FOO.

This example isn't supposed to demonstrate the usefulness of closures, just 
the difference in behaviour when compared to global variables. Possibly, with 
LISP-like dynamic scoping, a function could access a local variable from a 
calling scope, but to my best knowledge, Ruby is a lexically scoped language.

David Vallner