国产探花免费观看_亚洲丰满少妇自慰呻吟_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)。這將產生以下結果:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 平江县| 喀喇沁旗| 灵寿县| 富锦市| 嘉义市| 宁明县| 西盟| 万年县| 玉林市| 阜阳市| 甘谷县| 荃湾区| 会泽县| 三明市| 蓝田县| 岗巴县| 盐边县| 新野县| 增城市| 博爱县| 准格尔旗| 台山市| 桂阳县| 礼泉县| 紫云| 阳曲县| 山东省| 即墨市| 扬州市| 巴林右旗| 伊金霍洛旗| 宜宾市| 来凤县| 尉氏县| 寿宁县| 阿合奇县| 商水县| 长治县| 徐州市| 洪湖市| 中方县|