Any way to evaluate blocks using an arbitrary Binding?

K

Kenneth McDonald

Using Kernel.eval, I can evaluate a Ruby string under an arbitrary
variable Binding object. However, while I can obtain from a Proc the
Binding it uses when it is evaluated, there does not seem to be any way
of evaluating a Proc with a different Binding. Is this possible in some way?

Thanks,
Ken
 
R

Robert Klemme

Using Kernel.eval, I can evaluate a Ruby string under an arbitrary
variable Binding object. However, while I can obtain from a Proc the
Binding it uses when it is evaluated, there does not seem to be any way
of evaluating a Proc with a different Binding. Is this possible in some
way?

Sort of: you can use instance_eval and class_eval with a block. While
only "self" will be rebound this is sufficient in many cases.

Kind regards

robert
 
K

Kenneth McDonald

Robert,

I was already aware of instance_eval (have to look up class_eval) used
in this manner (possibly from another of your very useful postings), but
had wondered if there was a more general way of affecting the execution
environment. Oh well.

Thanks,
Ken
 
J

Joel VanderWerf

Kenneth said:
Robert,

I was already aware of instance_eval (have to look up class_eval) used
in this manner (possibly from another of your very useful postings), but
had wondered if there was a more general way of affecting the execution
environment. Oh well.

You can change the binding one variable at a time:

def foo
x = 1
proc {puts "x = #{x}"}
end

pr = foo

p eval("x", pr)
eval("x=2", pr)
p eval("x", pr)

pr.call

__END__

Output:

1
2
x = 2
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,019
Latest member
RoxannaSta

Latest Threads

Top