gpt4 book ai didi

ruby - Ruby 中 at_exit 和 END(大写)的区别

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

Kernel#at_exit 之间存在哪些差异(如果有)方法和 END (全部大写)关键字?后者仅仅是一种更 Perlish 的做事方式,而前者更像 Ruby 吗?

我尝试执行 defined?(END {puts "Bye"}),但出现语法错误。

最佳答案

“The Ruby Programming Language”定义了它们行为上的细微差别。 at_exit 可以在循环中多次调用,每次迭代调用都将在代码退出时执行。 END 只会在循环内调用一次。

...If an END statement is within a loop and is executed more than once, then the code associated with it is still only registered once:

a = 4;
if (true)
END { # This END is executed
puts "if"; # This code is registered
puts a # The variable is visible; prints "4"
}
else
END { puts "else" } # This is not executed
end
10.times {END { puts "loop" }} # Only executed once

The Kernel method at_exit provides an alternative to the END statement; it registers a block of code to be executed just before the interpreter exits. As with END blocks, the code associated with the first at_exit call will be executed last. If the at_exit method is called multiple times within a loop, then the block associated with it will be executed multiple times when the interpreter exits.

所以,运行:

2.times {
END { puts 'END'}
at_exit { puts 'at_exit' }
}

结果:

at_exitat_exitEND

关于ruby - Ruby 中 at_exit 和 END(大写)的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11731341/

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