Ruby中require、load、include、extend的區別介紹

來源:互聯網
上載者:User

   這篇文章主要介紹了Ruby中require、load、include、extend的區別介紹,require、load用於檔案,如.rb等等結尾的檔案,include、load則用於包含一個檔案中的模組,需要的朋友可以參考下

  require,load用於檔案,如.rb等等結尾的檔案。include,load則用於包含一個檔案中的模組。

  require 一般情況下用於載入庫檔案,而load則用於載入設定檔。

  1、require:載入一個庫,並且只載入一次,如果多次載入會返回false。只有當要載入的庫位於一個分離的檔案中時才有必要使用require。使用時不需要加副檔名,一般放在檔案的最前面:

   代碼如下:

  require ‘test_library'

  2、load:

  load用來多次載入一個庫,必須指定副檔名:

   代碼如下:

  load ‘test_library.rb'

  3、extend:在定義類時使用,把module的執行個體方法作為當前類的類方法.

  代碼如下:

  module Test

  def class_type

  "This class is of type:#{self.class}"

  end

  end

  class TestClass

  extend Test

  end

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

  4、include:在定義類時使用,把module的執行個體方法作為當前類的執行個體方法. 把module的變數作為當前類的類變數.

  include並不會把module的執行個體方法拷貝到類中,只是做了引用,包含module的不同類都指向了同一個對象。如果你改變了module的定義,即使你的程式還在運行,所有包含module的類都會改變行為。

  代碼如下:

  module Test

  @a = 1

  def class_type

  "This class is of type:#{self.class}"

  end

  end

  class TestClass

  include Test

  end

  # puts TestClass.class_type #=> undefined method `class_type' for TestClass:Class (NoMethodError)

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.