如何在Ruby中将一个块传递给另一个? [英] How to pass a block to another in Ruby?
问题描述
假设我有以下操作:
a = Proc.new do
puts "start"
yield
puts "end"
end
还假设我将a
传递给另一个方法,该方法随后使用该块在另一个类上调用instance_eval
,那么现在如何将一个块传递给该方法的末尾,该方法在a
中产生.
Also assuming I pass a
to another method which subsequently calls instance_eval
on another class with that block, how can I now pass a block onto the end of that method which gets yielded in 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
中的a?
How can I pass the secondary block to a in the instance_eval
?
我需要这样的东西作为我正在工作的Ruby模板系统的基础.
I need something like this for the basis of a Ruby templating system I'm working on.
推荐答案
您不能在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()
.
这篇关于如何在Ruby中将一个块传递给另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!