传递给Ruby方法的隐式块参数可以使用yield
执行,或者可以使用block_given?
检查其存在性。我正在尝试促使该隐式块将其传递给另一种方法。
这可能吗?
((它可以访问我要询问的隐式块参数。用显式参数替换它不会削减它。)
您可以获取它,更重要的是给它一个名称以便您可以引用它,使用方法的参数列表中的&
和号一元前缀符号,例如:
#implicit, anonymous, cannot be referenced:
def foo
yield 23 if block_given?
end
foo {|i| puts i }
# 23
#explicit, named, can be referenced:
def bar(&blk)
yield 23 if block_given? # still works
blk.(42) if blk # but now it also has a name and is a `Proc`
end
bar {|i| puts i }
# 23
# 42
这是您的两个选择:
Proc