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

2024-01-12

假设我有以下过程:

a = Proc.new do
    puts "start"
    yield
    puts "end"
end

还假设我通过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

输出当然应该是:

start
this block is b!
end

如何将辅助块传递给 ainstance_eval?

我需要这样的东西作为我正在开发的 Ruby 模板系统的基础。


你不能使用yielda。相反,您必须通过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 中的新功能)允许您将参数传递给块。因此,我们可以传递 Proc 对象b作为参数a,可以用以下方式调用它Proc#call().

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Ruby 中将一个块传递给另一个块? 的相关文章

随机推荐