Joe Ruby MUDCRAP-CE said:
- Ruby has closures -- which seem to be returning procs from functions?
- Continuations may be planned for a future release of Ruby.
Continuations are hard, so I won't touch them. Very good examples here:
<
http://www.rubycentral.com/faq/rubyfaq-11.html>
Closures are something I can handle (I discuss them in my AppleScript
book, for example).
* A binding is an association of a name and a value.
* A free variable is a variable defined in a surrounding scope.
* A closure is block of code where free variables are bound in
accordance with the surrounding scope and (this is important) retain
that binding.
So, for example:
var = 7
p = Proc.new {puts var}
def hereGoesNothing
var = "yoho"
yield
end
hereGoesNothing &p # => 7
var = 200
hereGoesNothing &p # => 200
The block "{puts var}" is a closure. Its "var" is a free variable and is
therefore bound to the "var" in the surrounding scope, which is the
"var" set to 7 in the first line. So what we see is that the "var"
inside hereGoesNothing makes no difference. As we change the top-level
"var", its new value is used each time we execute the block. It doesn't
matter what we do with p; it will retain its bindings.
Here's another example (more like your procs from functions idea):
def proc_maker
var = 7
Proc.new {puts var}
end
p = proc_maker
p.call # => 7
Here, "var" exists only inside the method "proc_maker". When we come to
call p, there is no "var"! But that doesn't matter; the proc "{puts
var}" has retained the binding of "var" with 7 from the place where it
was bound to start with, inside the method.
m.