循环与迭代
while/until/for、loop do、times/upto/downto、break/next
循环与迭代
Ruby 有 while/until/for,但真正的瑰宝是 times/upto/downto——循环写得像英文一样自然。
学完本章你将: 掌握 while/until/for、times/upto/downto、break/next。
while / until
ruby
# while
i = 0
while i < 5
puts i
i += 1
end
# until(while not)
until i == 0
puts i
i -= 1
end
数字迭代器(Ruby 特色)
ruby
5.times { |i| puts i } # 0 1 2 3 4
5.times do |i| puts i end # 同上
1.upto(5) { |i| puts i } # 1 2 3 4 5
5.downto(1) { |i| puts i } # 5 4 3 2 1
(1..5).each { |i| puts i } # 1 2 3 4 5
# step 步长
(0..10).step(2) { |i| puts i } # 0 2 4 6 8 10
for 循环
ruby
for i in 0..4
puts i
end
# 但 Ruby 社区更推荐 .each——更函数式
(0..4).each { |i| puts i }
break / next / redo
ruby
# break —— 退出循环
# next —— 跳过本次
# redo —— 重做本次(不重新检查条件)
3.times do |i|
break if i == 2 # i=2 时退出
puts i # 0 1
end