When is it common to use eval, lambda and proc (anything more?)
Personally:
- I use proc for most cases where I want a closure, deferred code, or to
capture a block. No real reason.
- I use lambda when I really want to emphasise that the number of args
is significant, or when I really need a 'return'.
- I never use eval.
a=1 # local var!
din.call # do it now (as code would stand here)
Since you defined 'a' after 'din', doesn't it think the 'a' inside the
closure is a function call, rather than a local variable?
def x
a=2
din
end
din
# Qu2: How can I access the a inside x from here? (I know, I shouldn't
Shouldn't, and can't. The only way to get a local variable out of a
function is to return it, or to assign it to a variable in an outer scope
(like an @ivar or $global). In either case you get the *value *of the
variable, but not the variable itself.
Hi
Yes, seems vars have to be defined before.
What is deferred code (in difference to a closure) ?
Code I want to store and defer until later.
Could you give each an example?
A closure encloses a scope (trapping local variables). If my proc/lambda
doesn't refer to any variables in the outer scope I can't exactly call it a
closure.