how to do instance_eval with arguments

J

Jim Weirich

I'm prototyping a DSL and came across a situtation where I have a lambda
that I would like to give to instance_eval, but the lambda takes
arguments. Instance_eval will not supply any arguments when evaluating
the lambda and I don't see a straightforward way around this.

Any suggestions?

Here's a test case ...

class Dummy
def f
:dummy_value
end
end

def instance_eval_with_args(obj, *args, &block)
# Magic goes here to evaluate +block+ in the scope of
# +obj+, yet pass a list of argument values to the block.
end

class TestInstanceEvalWithArgs < Test::Unit::TestCase
def test_instance_eval_with_args
# Create a block that returns the value of an argument and a value
# of a method call to +self+. This is the basic functionality I
need.
block = lambda { |a| [a, f] }

assert_equal [:arg_value, :dummy_value],
instance_eval_with_args(Dummy.new, :arg_value, &block)
end
end
 
Y

Yukihiro Matsumoto

Hi,

In message "Re: how to do instance_eval with arguments"
|
|I'm prototyping a DSL and came across a situtation where I have a lambda
|that I would like to give to instance_eval, but the lambda takes
|arguments. Instance_eval will not supply any arguments when evaluating
|the lambda and I don't see a straightforward way around this.
|
|Any suggestions?

CVS HEAD (1.9) has instance_exec method that works exactly what you
want.

matz.
 
J

Jim Weirich

Yukihiro said:
|
|I'm prototyping a DSL and came across a situtation where I have a lambda
|that I would like to give to instance_eval, but the lambda takes
|arguments. Instance_eval will not supply any arguments when evaluating
|the lambda and I don't see a straightforward way around this.
|
|Any suggestions?

CVS HEAD (1.9) has instance_exec method that works exactly what you
want.

Excellent! I think Matz's time machine is every bit as good as
Guido's[1].
 

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,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top