假设我有以下过程:
a = Proc.new do
puts "start"
yield
puts "end"
end
Run Code Online (Sandbox Code Playgroud)
另外假设我传递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
Run Code Online (Sandbox Code Playgroud)
输出当然应该是:
start
this block is b!
end
Run Code Online (Sandbox Code Playgroud)
如何将辅助块传递给instance_eval?
我需要这样的东西作为我正在研究的Ruby模板系统的基础.
你不能使用收益率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
Run Code Online (Sandbox Code Playgroud)
yield仅适用于方法.在这个新代码中,我使用了instance_exec(Ruby 1.9中的新增功能),它允许您将参数传递给块.因此,我们可以将Proc对象b作为参数传递a给它,可以调用它Proc#call().