3

include v.s extend 以及 require 的差別

 2 years ago
source link: https://blog.niclin.tw/2016/11/05/include-v.s-extend-%E4%BB%A5%E5%8F%8A-require-%E7%9A%84%E5%B7%AE%E5%88%A5/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

include v.s extend

在Ruby裡,Class只能單一繼承,而為了保有DRY(Do not repeat yourself)的風格與彈性,ruby提供了module的概念。

module是一些method的集合,允許class以混入(mixin)的方式去取得這些method來避免重複的程式碼,在這個過程中可以使用include以及extend來辦到,但畢竟兩種寫法一定會有其差異存在,就讓我們用程式碼的方式來了解。

include

module Log 
  def class_type
    "This class is of type: #{self.class}"
  end
end

class TestClass 
  include Log 
end

tc = TestClass.new.class_type
puts tc #This class is of type: TestClass

從上述例子我們可以看到 include是讓class所產生的instance直接繼承module裡的method,有點相似JavaScript裡的function.prototype。

extend

module Log
  def class_type
    "This class is of type: #{self.class}"
  end
end

class TestClass
  extend Log
  # ...
end

tc = TestClass.class_type
puts tc  # This class is of type: TestClass

當用extend來替換掉include時,extend則是讓class具有module裡的method但不會繼承給instance。

如果你直接實例化 TestClass的話會得到一個NoMethodError。

Require

Require方法允許你載入外部的Library,聰明的是他會防止你重複加載一樣的外部函式庫,範例如下:

  puts "load this library."
puts(require './test_library')
puts(require './test_library')

#結果將為
# load this library.
# true
# false

當你重複載入一個library的時候,將會返回false值。

參考資源: - [宅] 宅男臥軌日記(2) - ruby中的include, extend及require - 基础 Ruby 中 Include, Extend, Load, Require 的使用区别


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK