循環是程式控制流程的核心。Ruby 提供了多種循環結構,從傳統的 while、until、for 到極具 Ruby 風格的迭代器方法。本文詳細解析各類循環語法、修飾符形式、控制流程關鍵字與最佳實踐。
基本語法:
while conditional [do]
code
end
條件為真時持續執行。範例:
#!/usr/bin/ruby
$i = 0
$num = 5
while $i < $num do
puts("Inside the loop i = #$i")
$i += 1
end
輸出 0 到 4。
code while condition
# 或
begin
code
end while conditional
begin...end while 保證至少執行一次:
#!/usr/bin/ruby
$i = 0
$num = 5
begin
puts("Inside the loop i = #$i")
$i += 1
end while $i < $num
條件為假時執行,與 while 互補:
until conditional [do]
code
end
範例:
#!/usr/bin/ruby
$i = 0
$num = 5
until $i > $num do
puts("Inside the loop i = #$i")
$i += 1
end
輸出 0 到 5(含邊界)。
code until conditional
# 或
begin
code
end until conditional
遍歷範圍或集合:
for variable [, variable ...] in expression [do]
code
end
範例:
#!/usr/bin/ruby
for i in 0..5
puts "Value of local variable is #{i}"
end
輸出 0 到 5。for...in 幾乎等同於 (expression).each do |variable| ... end,差異在於 for 不建立新的區域變數作用域。
Ruby 慣用 .each、.times、.upto 等方法:
(0..5).each do |i|
puts "Value of local variable is #{i}"
end
nil。範例——break:
#!/usr/bin/ruby
for i in 0..5
if i > 2 then break end
puts "Value of local variable is #{i}"
end
# 輸出 0, 1, 2
.each、.map 等),程式碼更簡潔、更具 Ruby 風格。break/next 簡化邏輯,減少巢狀層級。