8

假设我有以下过程:

a = Proc.new do
    puts "start"
    yield
    puts "end"
end

还假设我传递a给另一个方法,该方法随后instance_eval使用该块调用另一个类,我现在如何将一个块传递到该方法的末尾,该方法在a.

例如:

def do_something(a,&b)
    AnotherClass.instance_eval(&a) # how can I pass b to a here?
end

a = Proc.new do
    puts "start"
    yield
    puts "end"
end

do_something(a) do
    puts "this block is b!"
end

输出当然应该是:

start
this block is b!
end

如何将辅助块传递给instance_eval?

我需要这样的东西作为我正在研究的 Ruby 模板系统的基础。

4

2 回答 2

5

您不能在a. 相反,您必须传递一个Proc对象。这将是新代码:

def do_something(a,&b)
    AnotherClass.instance_exec(b, &a)
end

a = Proc.new do |b|
    puts "start"
    b.call
    puts "end"
end

do_something(a) do
    puts "this block is b!"
end

yield仅适用于方法。在这个新代码中,我使用instance_exec了(Ruby 1.9 中的新代码),它允许您将参数传递给块。因此,我们可以将 Proc 对象b作为参数传递给a,它可以使用Proc#call().

于 2012-07-03T16:06:03.753 回答
0
a=Proc.new 做 |b|
    放“开始”
    b.调用
    把“结束”
结尾
def do_something(a,&b)
  AnotherClass.instance_eval { a.call(b) }
结尾
于 2012-07-03T16:25:11.847 回答