1、首先是while循環和until循環
這是兩種相反的循環,舉例說明
x= 1
until x >100;
puts x;
x = x*2;
end
輸出
1
2
4
8
16
32
64
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
2
4
8
16
32
64
還可以在一行中使用until和while
x = 1;
x = x*2 until x > 100;
puts x;
x一直翻倍,一直到x>100輸出128
2、還有幾種迭代方式,類似C#中的for循環
1.upto(5) {|i| puts i}
也可以寫成這樣
1.upto(5) do |i|
puts i
end
輸出
1
2
3
4
5
與之相反的是
10.downto(5) do |i|
puts i
end
輸出10
9
8
7
6
5
如果要設置步長
1.step(10,2) do |n|
puts n
end
輸出
1
3
5
7
9
20.step(10,-2) do |n|
puts n
end
輸出
20
18
16
14
12
10
3、each循環
names=["carter","james","martin"]
names.each { |e| puts e }
和
names.each do |e|
puts e
end
效果是相同的,都輸出
carter
james
martin
5.times do
puts "time"
end
5.times {puts "time"}
效果相同
輸出
time
time
time
time
time
多行代碼推薦do end,單行代碼推薦{}