Ruby 中的“include”和“extend”的區別
使用 Ruby 的 **include** 關鍵字時,我們匯入的只是一個模組程式碼,但是我們不能直接透過該類訪問匯入模組中的方法,因為它基本上是一個父類的子類
另一方面,當我們在 Ruby 中使用 **extend** 關鍵字時,我們匯入的還是一個模組程式碼,但是方法是以類方法匯入的。如果我們嘗試使用該類的例項訪問我們匯入的方法,編譯器會丟擲一個錯誤。
現在讓我們在 Ruby 程式碼中使用這兩個關鍵字來了解它們的差異。
示例 1
請看下面的程式碼。
# Creating a module that contains a method module MyModule def first_method puts 'This is the First Method.' end end class First_Class include MyModule end class Second_Class extend MyModule end # object access First_Class.new.first_method # class access Second_Class.first_method
輸出
該程式碼會產生如下輸出。
This is the First Method. This is the First Method.
示例 2
現在讓我們考慮一個用例,我們希望匯入類上的例項方法以及類方法。在這種情況下,我們將同時使用 include 和 **extend** 關鍵字。
請看下面的程式碼
# Creating a module that contains a method
module MyModule
def logs(x)
puts x
end
end
class First_Class
include MyModule
extend MyModule
end
First_Class.new.logs("It's a chilly overcast day.")
First_Class.logs("Keep an umbrella with you.")輸出
該程式碼會產生如下輸出。
It's a chilly overcast day. Keep an umbrella with you.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP