gpt4 book ai didi

ruby - 如何将 block 传递给子方法?

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:45 26 4
gpt4 key购买 nike

假设我有以下代码:

def a(n, m, &block)
yield if block_given?
end

def a
# My question is here. When a is called, block might be or might not be
# given. Below line is obvious wrong. How to call b and properly pass
# block to b?
b(1, 2, &block)
end

a # call a without block

a { # call a with a block
puts "in block"
}

最佳答案

编写 a() 来接受一个 block 。它暗示是可选的,正如安德鲁编码(marshal)指出的那样,如果没有给出,将作为 &nil 传递。

def b(n, m, &block)
yield if block_given?
puts "no block" if !block_given?
end

def a( &block )
b(1, 2, &block)
end

a # call a without block

a { # call a with a block
puts "in block"
}

输出:

no block
in block

关于ruby - 如何将 block 传递给子方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22366698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com