如何在Ruby中将块传递给另一个块?
假设我有以下过程:
a = Proc.new do puts "start" yield puts "end" end
另外假设我传递给另一个方法,该方法随后在具有该块的另一个类上调用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模板系统的基础。
你不能在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中的新增function),它允许您将参数传递给块。 因此,我们可以将Proc对象b
作为参数传递给a
,可以使用Proc#call()
调用它。
a = Proc.new do | b | 把“开始” b.call 把“结束” 结束 def do_something(a,&b) AnotherClass.instance_eval {a.call(b)} 结束