假设我有以下过程:
a = Proc.new do
puts "start"
yield
puts "end"
end
还假设我将 a
传递给另一个方法,该方法随后使用该 block 在另一个类上调用 instance_eval
,我现在如何将一个 block 传递到该方法的末尾在 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
如何将辅助 block 传递给 instance_eval
中的 a?
我需要这样的东西作为我正在开发的 Ruby 模板系统的基础。
最佳答案
您不能在 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
仅适用于方法。在这个新代码中,我使用了 instance_exec
(Ruby 1.9 中的新功能),它允许您将参数传递给 block 。因此,我们可以将 Proc 对象 b
作为参数传递给 a
,后者可以使用 Proc#call()
调用它。
关于ruby - 如何在 Ruby 中将一个 block 传递给另一个 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11314622/