Ruby方法可以访问隐式块参数吗?

问题描述 投票:0回答:1

传递给Ruby方法的隐式块参数可以使用yield执行,或者可以使用block_given?检查其存在性。我正在尝试促使该隐式块将其传递给另一种方法。

这可能吗?

((它可以访问我要询问的隐式块参数。用显式参数替换它不会削减它。)

ruby closures block
1个回答
1
投票

您可以获取它,更重要的是给它一个名称以便您可以引用它,使用方法的参数列表中的&和号一元前缀符号,例如:

#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
© www.soinside.com 2019 - 2024. All rights reserved.