區塊是 Ruby 最獨特、最強大的特性之一,它讓程式碼片段能像資料一樣被傳遞、儲存與執行。本文深入探討區塊語法、yield 機制、參數傳遞、BEGIN/END 區塊,以及區塊與方法、Proc 物件的關係。
兩種等價形式:
{ statement1; statement2; ... }
# 或
do
statement1
statement2
...
end
慣例:單行用大括號,多行用 do...end。
yield 將控制權移交給關聯的區塊:
#!/usr/bin/ruby
def test
puts "You are in the method"
yield
puts "You are again back to the method"
yield
end
test { puts "You are in the block" }
輸出:
You are in the method
You are in the block
You are again back to the method
You are in the block
區塊參數置於 | | 之間:
#!/usr/bin/ruby
def test
yield 5
puts "You are in the method test"
yield 100
end
test { |i| puts "You are in the block #{i}" }
輸出:
You are in the block 5
You are in the method test
You are in the block 100
多參數:yield a, b 對應 test { |a, b| ... }。
同名方法透過 yield 呼叫區塊。若方法最後一個參數前加 &,區塊會轉為 Proc 物件綁定給該參數:
#!/usr/bin/ruby
def test(&block)
block.call
end
test { puts "Hello World!" }
# 輸出: Hello World!
檔案層級的掛鉤:
BEGIN { ... }:檔案載入時執行,按遇到順序執行。END { ... }:程式結束前執行,按相反順序執行。#!/usr/bin/ruby
BEGIN { puts "BEGIN code block" }
END { puts "END code block" }
puts "MAIN code block"
輸出:
BEGIN code block
MAIN code block
END code block
區塊本身不是物件,但可透過 Proc.new、lambda 或 -> 轉為物件,實現儲存、傳遞與多次呼叫。lambda 對參數數量檢查嚴格,return 行為也不同(lambda 返回呼叫者,Proc 返回定義處上下文)。
yield,效能優於 Proc 呼叫。&block 參數接收。