Ruby BEGIN 与 END 问题

xautjzd · May 26, 2013 · Last by xautjzd replied at May 26, 2013 · 4978 hits

通过实例学习 ruby 过程中,看到 BEGIN 与 END 的关键字,也大致了解其含义与用法,但是在网上还是很难找到其相关资料。这是什么原因呢?下面是我在一个网站上看到的相关解释,让我不解: While the ruby program is loading, you can execute code inside a special block labeled "BEGIN" - pretty nifty. After the interpretor has loaded the code, but before execution, you can execute code in the "END" block.

puts "main program running" END { puts "program ending" } BEGIN { puts "I'm loading" }

输出: I'm loading main program running program ending

上面的解释:“After the interpretor has loaded the code, but before execution”说 END 中的 block 是在加载完成后并且执行前执行。这让人费解。有人能指点下么

写过 awk 或者 perl 就明白了。

主要在 ruby -n 时有用

ruby -ne 'BEGIN{ i = 0 }; i += 1; END{ puts i }' < file_you_need_count_lines

#1 楼 @luikore 谢谢回答,没写过 awk 和 perl。我的意思是 END 中的代码为何是在加载完成后执行前执行呢?应该是其他代码都执行完之后程序即将结束时执行吧

#1 楼 @luikore 这个以前还真的不知道诶 ENG {}at_exit {}又有神马差异呢?

#3 楼 @iBachue 在多行模式下面 at_exit {} 就会把同一个 hook 注册 n 遍了

#2 楼 @xautjzd 那个解释本身就不通顺,字都写错了,不管它...

简单易用的 ruby 语法参考: http://ruby.on-page.net/

#5 楼 @luikore 谢谢,这个网站看着不错,就是字有点小

You need to Sign in before reply, if you don't have an account, please Sign up first.