Ruby中的迴圈

2021-06-17 21:20:37 字數 1554 閱讀 8488

1、首先是while迴圈和until迴圈

這是兩種相反的迴圈,舉例說明

x= 1

until x >100;

puts x;

x = x*2;

end

輸出 124

8163264

x= 1

until x <100;

puts x;

x = x*2;

break if x>200;

end

永遠都不會執行

而while與until正好相反

x= 1

while x <100;

puts x;

x = x*2;

end

輸出1

24816

3264

還可以在一行中使用until和while

x = 1;

x = x*2 until x > 100;

puts x;

x一直翻倍,一直到x>100

輸出128

2、還有幾種迭代方式,類似c#中的for迴圈

1.upto(5)
也可以寫成這樣

1.upto(5) do |i|

puts i

end

輸出 123

45與之相反的是

10.downto(5) do |i|

puts i

end

輸出109

8765

如果要設定步長

1.step(10,2) do |n|

puts n

end

輸出 135

79

20.step(10,-2) do |n|

puts n

end

輸出

2018

1614

1210

3、each迴圈

names=["carter","james","martin"]

names.each

names.each do |e| 

puts e

end

效果是相同的,都輸出

carter

james

martin

5.times do

puts "time"

end5.times

效果相同

輸出time

time

time

time

time

多行**推薦do end,單行**推薦{}

Ruby 迴圈結構

迴圈 1 while語句 適合任何型別迴圈的單純語句 while 條件do 反覆執行的動作 end 2 until語句 與while 相反,條件不成立時執行,實際上是 while 的 運算 until 條件do 重複執行的動作 end 3 for 語句for 變數in 開始的數值 結束的數值do 重...

ruby的正則迴圈查詢

寫了乙個從html中提取的helper方法,不過不知道怎麼讓正則乙個個匹配下去,似乎string.scan不能達到我的要求,所以還是用了遞迴方法,如下 def get only pic cbody,result results if results nil if no match,return it...

ruby 條件和迴圈

1.1 if else 語句if conditional then code elsif conditional then code end值為false和nil為假,其他都為真。請注意關鍵字elsif。通常我們省略保留字then,但若想在一行內寫出完整的 if 式,則使用then。例子如下 x 1...