如何在Ruby中将一个块传递给另一个?

8
假设我有以下存储过程:
a = Proc.new do
    puts "start"
    yield
    puts "end"
end

假设我将a传递给另一个方法,该方法随后在另一个类上调用instance_eval,那么我现在如何将一个块传递到该方法的末尾,并在其中yielda
例如:
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 中的 a?
我正在开发一个基于 Ruby 的模板系统,需要这样的功能。

可能是在块/lambda内部产生麻烦的重复问题。 - Ciro Santilli OurBigBook.com
2个回答

5

a 中不能使用 yield。相反,您必须传递一个 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 只能用于方法。在这段新代码中,我使用了 Ruby 1.9 中新增的 instance_exec,它允许你向代码块传递参数。因此,我们可以将 Proc 对象 b 作为参数传递给 a,后者可以使用 Proc#call() 调用它。


0
a = Proc.new do |b| puts "开始" b.call puts "结束" end
def do_something(a, &b) AnotherClass.instance_eval { a.call(b) } end

那行不通。instance_eval不能像普通块一样捕获变量。 - Linuxios

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接