###### tags: `Ruby on Rails 觀念` # 說明include與extend的差異在哪裡? 延續上一章 Module 和 Class 的關係,在引入 Module 就產生了兩種方式,第一種是 include,另一種是 extend 。 ## include 引用 Module 方法到 Class ```rb module Jam def taste puts "有巧克力口味了!!" end end class Bread include Jam # 引入 Jam 模組 end toast = Bread.new toast.taste # taste 是實體方法 # toast.taste => 有巧克力口味了!! ``` include 模組之後,該模組裡面定義的所有方法**都會變成 Class 裡面所有的實體方法**。 參照上方原始碼,taste 方法作用在實體變數 toast 身上,也就是說 taste 是成為一個實體方法,它作用在 toast 這個實體上。 ## extend 可以擴充 module 方法到 Class,增加類別方法,但不會產生實體方法 (instance method) ```rb module Jam def taste puts "有巧克力口味了!!" end end class Bread extend Jam # 擴充 Jam 模組 end Bread.taste # 成功,屬於類別方法 => 有巧克力口味了!! toast = Bread.new toast.taste # 錯誤 => undefined method `taste' ``` extend 模組之後,該模組裡面定義的所有方法**都會變成 Class 裡面所有的類別方法**。 參照上方原始碼,extend 可以讓 Cat 增加類別方法。 ## 結論 include 是增加 Class 的實體方法,而是 extend 增加 Class 的類別方法。 ### 參考 [類別方法與實體方法差異](https://ithelp.ithome.com.tw/articles/10236100) [關於模組(Module)](https://ithelp.ithome.com.tw/articles/10192295)