由于 Ruby 提供了很多便捷的方法进行对象的循环遍历,如:Array#each、Integer#times、Integer#downto、Integer#upto、Kernel#loop 等,所以日常的开发中很少会需要写循环语句。便整理了相关内容,方便日后查看参考。

Ruby 中的循环语句有 for...inwhileuntil 三种,具体使用方法如下:

for…in

遍历集合中的所有成员

for i in 0..3
  puts i
end

while

当条件成立时,执行循环体

i = 0
while i <= 3 do  # do 可以省略
  puts i
  i += 1
end

while 可以后置,循环体至少执行一次

i = 0
begin
  puts i
  i += 1
end while i <= 3

until

当条件不成立时,执行循环体

i = 0
until i > 3 do  # do 可以省略
  puts i
  i += 1
end

和 while 一样,until 也可以后置,循环体至少执行一次

i = 0
begin
  puts i
  i += 1
end until i > 3

参考:

  1. Ruby学习札记(7)-Ruby中具有循环控制的方法和语句大归纳
  2. Ruby While and Until Loops
  3. Looping with for and the Ruby Looping Methods
  4. Ruby Loops - while, for, until, break, redo and retry