我期待代码
foo=proc{puts "foo"}
instance_exec(1,2,3,&foo) do |*args , &block|
puts *args
block.call
puts "bar"
end
Run Code Online (Sandbox Code Playgroud)
输出
1 2 3 foo bar
但得到了错误
both block arg and actual block given
我可以将一个本身期望块的块传递给ruby中的instance_exec吗?
&foo尝试foo作为块传递给instance_exec,而您已经在传递一个显式块。省略foo与号就像任何其他参数一样发送(除了它是一个Proc实例)。所以,试试这个:
instance_exec(1,2,3,foo) do |*args, block|
puts *args
block.call
puts "bar"
end
Run Code Online (Sandbox Code Playgroud)
这也意味着您可以执行以下操作:
bar = proc{ |*args, block|
puts *args
block.call
puts "bar"
}
instance_exec(1,2,3,foo,&bar)
Run Code Online (Sandbox Code Playgroud)
并得到相同的结果。
更多信息见 Ruby 中 block 和 &block 的区别
| 归档时间: |
|
| 查看次数: |
901 次 |
| 最近记录: |