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,单行代码推荐{}