gpt4 book ai didi

ruby - 在匿名 block 中产生

转载 作者:数据小太阳 更新时间:2023-10-29 07:13:06 25 4
gpt4 key购买 nike

我没有理解以下行为(另请参阅 in this SO thread):

def def_test
puts 'def_test.in'
yield if block_given?
puts 'def_test.out'
end

def_test do
puts 'def_test ok'
end

block_test = proc do |&block|
puts 'block_test.in'
block.call if block
puts 'block_test.out'
end

block_test.call do
puts 'block_test'
end

proc_test = proc do
puts 'proc_test.in'
yield if block_given?
puts 'proc_test.out'
end

proc_test.call do
puts 'proc_test ok'
end

输出:

def_test.in
def_test ok
def_test.out
block_test.in
block_test ok
block_test.out
proc_test.in
proc_test.out

我不介意求助于显式声明 &block 变量并直接调用它,但我更希望弄清楚为什么我最终需要这样做。

最佳答案

block_given? 考虑 def 范围,而不是 lambda 范围:

def test
l = lambda do
yield if block_given?
end
l.call
end

test { puts "In block" }

关于ruby - 在匿名 block 中产生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6613323/

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