Ruby循环 #

一、循环概述 #

Ruby提供了多种循环语句来重复执行代码块。

语句 描述
while 条件为真时循环
until 条件为假时循环
for 遍历集合
loop 无限循环

二、while循环 #

2.1 基本while #

ruby
i = 0

while i < 5
  puts i
  i += 1
end

2.2 while修饰符 #

ruby
i = 0

puts i while i < 5
i += 1 while i < 5

begin
  puts i
  i += 1
end while i < 5

2.3 while返回值 #

ruby
i = 0
result = while i < 5
          i += 1
        end

result

2.4 实用示例 #

ruby
def countdown(n)
  while n > 0
    puts n
    n -= 1
    sleep 1
  end
  puts "发射!"
end

countdown(5)

三、until循环 #

3.1 基本until #

ruby
i = 0

until i >= 5
  puts i
  i += 1
end

3.2 until修饰符 #

ruby
i = 0

puts i until i >= 5
i += 1 until i >= 5

begin
  puts i
  i += 1
end until i >= 5

3.3 until vs while not #

ruby
until condition
  do_something
end

while !condition
  do_something
end

3.4 实用示例 #

ruby
def wait_for(condition)
  until condition.call
    sleep 0.1
  end
end

wait_for(-> { File.exist?("output.txt") })

四、for循环 #

4.1 基本for #

ruby
for i in 1..5
  puts i
end

for item in ["apple", "banana", "cherry"]
  puts item
end

4.2 for与范围 #

ruby
for i in 1..10
  puts i if i.even?
end

for i in 1...10
  puts i
end

4.3 for与数组 #

ruby
arr = [1, 2, 3, 4, 5]

for item in arr
  puts item * 2
end

for i in 0...arr.length
  puts "arr[#{i}] = #{arr[i]}"
end

4.4 for与哈希 #

ruby
hash = { a: 1, b: 2, c: 3 }

for key, value in hash
  puts "#{key}: #{value}"
end

4.5 for vs each #

ruby
for i in [1, 2, 3]
  puts i
end

[1, 2, 3].each do |i|
  puts i
end

for i in [1, 2, 3]
  x = i
end
x

[1, 2, 3].each do |i|
  y = i
end
y

五、loop循环 #

5.1 基本loop #

ruby
i = 0

loop do
  puts i
  i += 1
  break if i >= 5
end

5.2 无限循环 #

ruby
loop do
  puts "运行中..."
  sleep 1
end

5.3 带条件的loop #

ruby
i = 0

loop do
  i += 1
  next if i.even?
  puts i
  break if i >= 10
end

5.4 loop返回值 #

ruby
result = loop do
  break "完成"
end

result

六、循环控制 #

6.1 break #

ruby
i = 0

while true
  puts i
  i += 1
  break if i >= 5
end

[1, 2, 3, 4, 5].each do |n|
  break if n > 3
  puts n
end

6.2 next #

ruby
(1..10).each do |n|
  next if n.even?
  puts n
end

i = 0
while i < 10
  i += 1
  next if i.even?
  puts i
end

6.3 redo #

ruby
i = 0

while i < 5
  i += 1
  puts "i = #{i}"
  redo if i == 3
end

6.4 retry #

ruby
def fetch_with_retry(url, max_retries = 3)
  retries = 0
  begin
    fetch(url)
  rescue NetworkError
    retries += 1
    retry if retries < max_retries
    raise
  end
end

6.5 带返回值的break #

ruby
result = [1, 2, 3, 4, 5].each do |n|
  break n * 2 if n > 3
end

result

七、嵌套循环 #

7.1 基本嵌套 #

ruby
for i in 1..3
  for j in 1..3
    puts "#{i}, #{j}"
  end
end

7.2 循环标签模拟 #

ruby
found = false

for i in 1..5
  for j in 1..5
    if i * j == 12
      puts "Found: #{i} * #{j} = 12"
      found = true
      break
    end
  end
  break if found
end

7.3 使用catch/throw #

ruby
catch :found do
  for i in 1..5
    for j in 1..5
      if i * j == 12
        puts "Found: #{i} * #{j} = 12"
        throw :found
      end
    end
  end
end

八、实用示例 #

8.1 斐波那契数列 #

ruby
def fibonacci(n)
  a, b = 0, 1
  result = []

  while result.length < n
    result << a
    a, b = b, a + b
  end

  result
end

puts fibonacci(10).join(", ")

8.2 阶乘 #

ruby
def factorial(n)
  result = 1
  i = 1

  while i <= n
    result *= i
    i += 1
  end

  result
end

puts factorial(5)

8.3 猜数字游戏 #

ruby
def guess_number
  target = rand(1..100)
  guesses = 0

  loop do
    print "猜一个数字 (1-100): "
    guess = gets.chomp.to_i
    guesses += 1

    case guess <=> target
    when -1
      puts "太小了!"
    when 1
      puts "太大了!"
    when 0
      puts "恭喜! 你用了 #{guesses} 次猜对了!"
      break
    end
  end
end

8.4 进度条 #

ruby
def progress_bar(total)
  i = 0

  while i < total
    i += 1
    percent = (i.to_f / total * 100).to_i
    bar = "=" * (percent / 2) + " " * (50 - percent / 2)
    print "\r[#{bar}] #{percent}%"
    sleep 0.1
  end

  puts "\n完成!"
end

progress_bar(100)

8.5 菜单系统 #

ruby
def menu_system
  loop do
    puts "\n=== 菜单 ==="
    puts "1. 选项一"
    puts "2. 选项二"
    puts "3. 退出"
    print "请选择: "

    choice = gets.chomp

    case choice
    when "1"
      puts "执行选项一"
    when "2"
      puts "执行选项二"
    when "3"
      puts "再见!"
      break
    else
      puts "无效选择"
    end
  end
end

九、最佳实践 #

9.1 优先使用迭代器 #

ruby
for i in 1..10
  puts i
end

(1..10).each { |i| puts i }

9.2 避免无限循环 #

ruby
loop do
  process
end

loop do
  break if should_exit?
  process
end

9.3 使用有意义的循环变量 #

ruby
for i in 0...arr.length
  puts arr[i]
end

arr.each_with_index do |item, index|
  puts "#{index}: #{item}"
end

9.4 避免深层嵌套 #

ruby
while condition1
  while condition2
    while condition3
      do_something
    end
  end
end

while condition1 && condition2 && condition3
  do_something
end

十、总结 #

本章我们学习了:

  1. while循环:条件为真时循环
  2. until循环:条件为假时循环
  3. for循环:遍历集合
  4. loop循环:无限循环
  5. 循环控制:break、next、redo、retry
  6. 嵌套循环:多层循环、catch/throw
  7. 最佳实践:优先使用迭代器、避免无限循环

接下来让我们学习Ruby的循环控制!

最后更新:2026-03-27