且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-30 13:43:04

您不能在a中使用yield.相反,您必须传递Proc对象.这将是新代码:

You can't use yield in a. Rather, you have to pass a Proc object. This would be the new code:

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中的新增功能),它允许您将参数传递给块.因此,我们可以将Proc对象b作为参数传递给a,该对象可以使用Proc#call()进行调用.

yield is only for methods. In this new code, I used instance_exec (new in Ruby 1.9) which allows you to pass parameters to the block. Because of that, we can pass the Proc object b as a parameter to a, which can call it with Proc#call().