萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 區塊深度解析:yield、參數傳遞、BEGIN/END 與 Proc 物件

區塊是 Ruby 最獨特、最強大的特性之一,它讓程式碼片段能像資料一樣被傳遞、儲存與執行。本文深入探討區塊語法、yield 機制、參數傳遞、BEGIN/END 區塊,以及區塊與方法、Proc 物件的關係。

區塊語法

兩種等價形式:

{ statement1; statement2; ... }
# 或
do
  statement1
  statement2
  ...
end

慣例:單行用大括號,多行用 do...end。

yield 執行區塊

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

yield 傳遞參數

區塊參數置於 | | 之間:

#!/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 區塊

檔案層級的掛鉤:

  • 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 與 Lambda

區塊本身不是物件,但可透過 Proc.new、lambda 或 -> 轉為物件,實現儲存、傳遞與多次呼叫。lambda 對參數數量檢查嚴格,return 行為也不同(lambda 返回呼叫者,Proc 返回定義處上下文)。

實務建議

  • 優先使用區塊配合 yield,效能優於 Proc 呼叫。
  • 需要儲存區塊供稍後執行時,使用 &block 參數接收。
  • 領域特定語言(DSL)大量依賴區塊語法(如 Rails 路由、RSpec 測試)。
copyright © 萬盛學電腦網 all rights reserved