国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

詳解Ruby中的循環語句的用法

2019-10-26 19:25:37
字體:
來源:轉載
供稿:網友

Ruby 中的循環用于執行相同的代碼塊若干次。本章節將詳細介紹 Ruby 支持的所有循環語句。
Ruby while 語句
語法

while conditional [do]  codeend

當 conditional 為真時,執行 code。while 循環的 conditional 通過保留字 do、一個換行符、反斜線 / 或一個分號 ; ,來與 code 分離開。
實例

#!/usr/bin/ruby $i = 0$num = 5 while $i < $num do  puts("Inside the loop i = #$i" )  $i +=1end

這將產生以下結果:

Inside the loop i = 0Inside the loop i = 1Inside the loop i = 2Inside the loop i = 3Inside the loop i = 4

Ruby while 修飾符
語法

code while condition OR begin codeend while conditional

當 conditional 為真時,執行 code。

如果 while 修飾符跟在一個沒有 rescue 或 ensure 子句的 begin 語句后面,code 會在 conditional 判斷之前執行一次。
實例

#!/usr/bin/ruby $i = 0$num = 5begin  puts("Inside the loop i = #$i" )  $i +=1end while $i < $num

這將產生以下結果:

Inside the loop i = 0Inside the loop i = 1Inside the loop i = 2Inside the loop i = 3Inside the loop i = 4Ruby until 語句until conditional [do]  codeend

當 conditional 為假時,執行 code。until 語句的 conditional 通過保留字 do、一個換行符或一個分號,來與 code 分離開。
實例

#!/usr/bin/ruby $i = 0$num = 5 until $i > $num do  puts("Inside the loop i = #$i" )  $i +=1;end

這將產生以下結果:

Inside the loop i = 0Inside the loop i = 1Inside the loop i = 2Inside the loop i = 3Inside the loop i = 4Inside the loop i = 5Ruby until 修飾符語法code until conditional OR begin  codeend until conditional

當 conditional 為假時,執行 code。

如果 until 修飾符跟在一個沒有 rescue 或 ensure 子句的 begin 語句后面,code 會在 conditional 判斷之前執行一次。
實例

#!/usr/bin/ruby $i = 0$num = 5begin  puts("Inside the loop i = #$i" )  $i +=1;end until $i > $num

這將產生以下結果:

Inside the loop i = 0Inside the loop i = 1Inside the loop i = 2Inside the loop i = 3Inside the loop i = 4Inside the loop i = 5

Ruby for 語句
語法

for variable [, variable ...] in expression [do]  codeend

針對 expression 中的每個元素分別執行一次 code。
實例

#!/usr/bin/ruby for i in 0..5  puts "Value of local variable is #{i}"end

在這里,我們已經定義了范圍 0..5。語句 for i in 0..5 允許 i 的值從 0 到 5(包含 5)。這將產生以下結果:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 陈巴尔虎旗| 屏南县| 金溪县| 加查县| 香河县| 三门峡市| 商河县| 新营市| 武隆县| 璧山县| 桦南县| 许昌市| 宜君县| 睢宁县| 钦州市| 石门县| 麻城市| 沈丘县| 循化| 亳州市| 库伦旗| 内丘县| 东乌| 汕头市| 岐山县| 三江| 扎赉特旗| 邹城市| 华阴市| 呈贡县| 财经| 遵化市| 清徐县| 司法| 阿拉善盟| 托克逊县| 象州县| 泾源县| 株洲市| 潼关县| 莎车县|