Ruby中的循環用于執行相同的代碼塊指定的次數。本章將詳細介紹Ruby支持的循環語句。
Ruby while 語句:
語法:
while conditional [do]
code
end
執行代碼當條件為true時。while循環的條件是代碼中的保留字,換行,反斜杠(/)或一個分號隔開。
實例:
#!/usr/bin/ruby$i = 0$num = 5while $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
code
end while conditional
執行代碼,當條件為true。
如果while 修飾符緊跟一個begin 語句但是沒有 rescue 或 ensure 子句, 代碼被執行前一次條件求值。
實例:
#!/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 = 4
Ruby until 語句:
until conditional [do]
code
end
執行代碼當條件為false。until 條件語句從代碼分離的保留字,換行符或分號。
語句:
#!/usr/bin/ruby$i = 0$num = 5until $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 = 5
Ruby until 修辭符:
語法:
code until conditional
OR
begin
code
end until conditional
執行代碼當條件為 false。
如果 until 修辭符跟著 begin 語句但沒有 rescue 或 ensure 子句, 代碼一旦被執行在條件求值之前。
例子:
#!/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]
code
end
一次執行代碼的每個元素在 in 表達式。
實例:
#!/usr/bin/rubyfor i in 0..5 puts "Value of local variable is #{i}"end
這里我們定義的范圍 0 .. 5 。因為在語句 for i in 0..5 將允許取值的范圍從0到5(含5),這將產生以下結果:
Value of local variable is 0Value of local variable is 1Value of local variable is 2Value of local variable is 3Value of local variable is 4Value of local variable is 5
新聞熱點
疑難解答