簡體   English   中英

ruby文檔中的module_function示例

[英]module_function example in the ruby documentation

我在ruby文檔的module_function中看到了該示例。 我不明白代碼的后半部分,其中Mod.one返回舊的“這是一個”,而c.one返回更新的“這是新的”。 這是怎么發生的

這是文檔中的實際代碼

 module Mod
   def one
     "This is one"
   end
   module_function :one
 end

 class Cls
   include Mod
   def call_one
     one
   end
 end

 Mod.one     #=> "This is one"
 c = Cls.new
 c.call_one  #=> "This is one"

 module Mod
   def one
     "This is the new one"
   end
 end

 Mod.one     #=> "This is one"
 c.call_one   #=> "This is the new one"

為什么Mod.one返回舊代碼,但Cls對象能夠訪問新代碼? 謝謝。

運行module_function會在模塊級別復制一個功能,即,它等效於以下代碼:

module Mod
  def Mod.one
    "This is one"
  end

  def one
    "This is the new one"
  end
end

Mod.oneone不同的方法。 可以在任何地方調用第一個,當您將模塊包含在類中時,第二個成為實例方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM