ZetCode

Ruby while 关键字

最后修改日期:2025 年 4 月 27 日

本教程将解释如何使用 Ruby 的 while 关键字创建循环。while 循环在条件为真时重复执行代码。

while 关键字创建一个只要其条件评估为真就一直运行的循环。它在每次迭代之前检查条件。当条件变为假时,循环终止。

while 循环是 Ruby 中重复任务的基础。当预先不知道重复次数时,它们可以精确控制迭代。

基本 while 循环

此示例演示了 while 循环的最简单形式。循环在条件保持为真时继续。

basic_while.rb
count = 0

while count < 5
  puts "Count is #{count}"
  count += 1
end

puts "Loop finished"

count 小于 5 时,循环运行。每次迭代都会打印当前的计数并将其递增。当 count 达到 5 时,循环退出。

带用户输入的 while 循环

此示例使用 while 重复提示用户输入,直到满足特定条件。

user_input.rb
answer = ""

while answer.downcase != "quit"
  print "Enter a command (or 'quit' to exit): "
  answer = gets.chomp
  puts "You entered: #{answer}"
end

puts "Goodbye!"

循环一直持续到用户输入“quit”。条件以不区分大小写的方式检查输入。每次迭代都会处理用户的输入。

带 break 的无限 while 循环

此示例显示如何使用 while true 创建一个无限循环,并使用 break 根据条件退出。

infinite_loop.rb
counter = 0

while true
  puts "Counter: #{counter}"
  counter += 1
  
  break if counter >= 10
end

puts "Loop exited"

循环会无限运行,直到满足 break 条件。当退出条件复杂或出现在循环中间时,这种模式很有用。

带 next 关键字的 while 循环

此示例演示了在 while 循环中使用 next 来跳过某些迭代。

next_keyword.rb
num = 0

while num < 10
  num += 1
  next if num.even?
  
  puts "Odd number: #{num}"
end

puts "Done"

循环使用 next 跳过偶数。只打印奇数。循环一直持续到处理完所有小于或等于 10 的数字。

while 修饰符形式

Ruby 提供了一个后缀 while 修饰符,可在条件为真时执行代码。这种简洁的形式对于单语句循环很有用。

modifier_form.rb
count = 0

puts count += 1 while count < 5

puts "Final count: #{count}"

后缀 while 会重复执行前面的语句。当条件变为假时,循环停止。这种形式紧凑但灵活性较低。

嵌套 while 循环

此示例演示了嵌套的 while 循环以创建更复杂的迭代模式。

nested_loops.rb
outer = 1

while outer <= 3
  inner = 1
  
  while inner <= outer
    print "#{outer}:#{inner} "
    inner += 1
  end
  
  puts
  outer += 1
end

外层循环运行三次。内层循环的迭代次数随外层迭代次数的增加而增加。这会创建一个三角数模式。

带数组的 while 循环

此示例展示了如何使用 while 处理数组元素,而不使用迭代器方法。

array_processing.rb
fruits = ["apple", "banana", "cherry", "date"]
index = 0

while index < fruits.length
  puts "Fruit ##{index + 1}: #{fruits[index].capitalize}"
  index += 1
end

puts "All fruits processed"

循环通过索引处理每个数组元素。它一直持续到访问完所有元素。这种方法提供了对数组遍历的手动控制。

来源

Ruby 关键字文档

本教程涵盖了 Ruby 的 while 循环,并通过实际示例展示了基本用法、控制流和常见模式。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 Ruby 教程