# Ruby 循环语句

## 1. while

`while` 循环旨在重复执行命令直到不满足条件，语法如下：

``````i = 0
while i < 5 do
puts i
i += 1
end

# ---- 输出结果 ----
0
1
2
3
4
``````

**经验：**我们在实际开发中会省略 `do`

``````i = 0
while i < 5
puts i
i += 1
end

# ---- 输出结果 ----
0
1
2
3
4
``````

``````i = 0
while i < 5
puts i
i += 1
break if i == 2
end

# ---- 输出结果 ----
0
1
``````

## 2. until

`until``while` 相反，它旨在重复执行直到条件满足为止

``````i = 0
until i == 5
puts i
i += 1
end

# ---- 输出结果 ----
0
1
2
3
4
``````

`until`也可以用作语句修饰符，后置使用：

``````i = 0
puts i += 1 until i == 5

# ---- 输出结果 ----
1
2
3
4
5
``````

## 3. for…in

for 循环是经典的循环构造，它允许任务重复特定的次数。Ruby 不同点在于，它可以和范围（Range）结合。

``````for i in 1..8 do
puts i
end

# ---- 输出结果 ----
1
2
3
4
5
6
7
8
``````

``````for i in 1..8 do puts i end

# ---- 输出结果 ----
1
2
3
4
5
6
7
8
``````

``````for j in 1..5 do
for i in 1..5 do
print i,  " "
end
puts
end

# ---- 输出结果 ----
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
``````

``````for j in 1..5 do
for i in 1..5 do
print i,  " "
break if i == 2
end
end

# ---- 输出结果 ----
1 2
1 2
1 2
1 2
1 2
``````

`next` 会调到下一次循环。

``````for j in 1..5 do
for i in 1..5 do
next if i == 2
print i,  " "
end
end

# ---- 输出结果 ----
1 3 4 5
1 3 4 5
1 3 4 5
1 3 4 5
1 3 4 5
``````