Ruby 開發者常在 require、load、include、extend 之間混淆。本文從文件載入、模組混入兩大維度,系統釐清四者的本質差異、適用場景與底層機制,並附上可執行代碼範例驗證行為。
| 關鍵字 | 作用對象 | 核心功能 | 執行頻次 |
|---|---|---|---|
require | 文件 (.rb) | 載入庫文件,全局唯一 | 一次 |
load | 文件 (.rb) | 載入配置/腳本,可重複執行 | 多次 |
include | 模組 | 混入實例方法 | 每次 include |
extend | 模組 | 混入類別/單例方法 | 每次 extend |
# 載入標準庫或 Gem,自動補全 .rb 副檔名,只執行一次
require 'json'
require 'active_support/all'
# 重複 require 返回 false
require 'json' # => false
特點: 追蹤 $LOADED_FEATURES 防止重複載入;搜尋路徑來自 $LOAD_PATH;通常置於文件頂部。
# 必須指定完整副檔名,每次呼叫都會重新執行文件內容
load 'config/settings.rb'
load 'config/settings.rb' # 再次執行
# 可選第二參數 wrap=true,將載入內容包裹在匿名模組中,避免污染全局命名空間
load 'plugin.rb', true
適用場景: 開發環境熱重載配置、插件系統動態載入。
module Test
@a = 1 # 模組實例變數
def class_type
"This class is of type: #{self.class}"
end
end
class TestClass
include Test
end
# 實例方法可用
TestClass.new.class_type # => "This class is of type: TestClass"
# 類別方法不可用
# TestClass.class_type # => NoMethodError
# 修改模組定義即時生效(引用關係)
module Test
def new_method; "dynamic"; end
end
TestClass.new.new_method # => "dynamic"
關鍵機制: include 建立的是引用關係,而非複製方法。所有包含該模組的類別共享同一方法表,修改模組即時影響所有類別。
module Test
def class_type
"This class is of type: #{self.class}"
end
end
class TestClass
extend Test
end
# 類別方法可用
TestClass.class_type # => "This class is of type: Class"
# 單例方法示例
obj = Object.new
obj.extend Test
obj.class_type # => "This class is of type: Object"
module M
def hello; "M"; end
end
class C
include M # 方法查找順序:C -> M -> Object
# prepend M # 順序:M -> C -> Object
# extend M # 單例類別順序:# -> M -> Class
end
@a 會成為類別的類別變數,所有子類共享obj.extend M 修改的是該對象的單例類別,不影響同類別其他實例$LOADED_FEATURES 自動處理,但邏輯依賴順序時需注意理解四者本質差異,能讓你在設計 Ruby 程式架構時,精準選擇正確的代碼組織與復用方式,寫出更符合 Ruby 風格的優雅代碼。