Ruby入門介紹第2/5頁(yè)
更新時(shí)間:2007年10月20日 19:00:36 作者:
二、BEGIN & END
BEGIN 塊
BEGIN 塊中的代碼在所有代碼執(zhí)行之前執(zhí)行,Ruby 允許設(shè)置多個(gè) BEGIN 塊并按出現(xiàn)的順序執(zhí)行塊中的代碼。C# 程序員注意下面的代碼
BEGIN { print "OnInit(object sender, EventArgs args)\n" } BEGIN { print "OnLoad(object sender, EventArgs args)\n" } print "Running"
BEGIN{ print "OnInit(object sender, EventArgs args)\n" } BEGIN{ print "OnLoad(object sender, EventArgs args)\n" } print "Running"
1i = 0 2while i < 10 3 # 雖然處理循環(huán)結(jié)構(gòu)中,但 BEGIN 塊內(nèi)的代碼仍然只執(zhí)行一次 4 BEGIN{ 5 print "OnInit(object sender, EventArgs args)\n" 6 } 7 i += 1 8end 9 10if false 11 # BEGIN 完全不受 if 的影響,只要出現(xiàn) BEGIN 塊就會(huì)得到執(zhí)行 12 BEGIN{ 13 print "OnLoad(object sender, EventArgs args)\n" 14 } 15end 16 17print "Running"
print "OnLoad(object sender, EventArgs args)\n" BEGIN{ print "OnInit(object sender, EventArgs args)\n" } print "Running"
END 塊與 BEGIN 塊相反,在所有代碼執(zhí)行之后執(zhí)行,多個(gè) END 塊時(shí)最先出現(xiàn)的 END 塊最后執(zhí)行。除此之外,END 塊雖然不受 while 的影響,但是可能通過(guò) if 來(lái)控制 END 塊的執(zhí)行與否。比如下面代碼的輸出結(jié)果就是 Start - Load - Unload。
if false END{ # 永遠(yuǎn)不輸出 print "Init" } end END{ # 最后輸出 print "Unload\n" } END{ # 先于 Unload 輸出 print "Load\n" } # 最先輸出 print "Start\n"
相關(guān)文章
Ruby環(huán)境下安裝使用bundler來(lái)管理多版本的gem
這篇文章主要介紹了Ruby環(huán)境下安裝使用bundler來(lái)管理多版本的gem的方法,舉了Ruby On Rails中的應(yīng)用實(shí)例來(lái)進(jìn)行演示,需要的朋友可以參考下2016-06-06Ruby中的類Google Map/Reduce框架Skynet介紹
這篇文章主要介紹了Ruby中的類Google Map/Reduce框架Skynet介紹,Skynet是一款創(chuàng)建分布式應(yīng)用程序的框架,需要的朋友可以參考下2015-01-01Luhn算法學(xué)習(xí)及其Ruby版實(shí)現(xiàn)代碼示例
Luhn算法主要北用來(lái)進(jìn)行數(shù)字驗(yàn)證,尤其是卡號(hào)身份證號(hào)等,這里我們就來(lái)看一下Luhn算法學(xué)習(xí)及其Ruby版實(shí)現(xiàn)代碼示例:2016-05-05