2017-04-21 65 views
1

爲什麼下面的代碼給出了下面的錯誤?'包含'模塊,但仍不能調用方法

require 'open3' 

module Hosts 
    def read 
    include Open3 
    popen3("cat /etc/hosts") do |i,o,e,w| 
     puts o.read 
    end 
    end 
end 

Hosts.read 
#=> undefined method `popen3' for Hosts:Class (NoMethodError) 

它的工作原理,如果我用全路徑即Open3::popen3調用popen3。但我已經include -ed了,所以認爲我不需要Open3::位?

感謝

回答

0

您已經定義了一個實例方法,但嘗試使用它作爲單方法。爲了讓你想有可能的,你還必須extendOpen3,不include

module Hosts 
    extend Open3 

    def read 
    popen3("cat /etc/hosts") do |i,o,e,w| 
     puts o.read 
    end 
    end 
    module_function :read # makes it available for Hosts 
end 

現在:

Hosts.read 
## 
# Host Database 
# 
# localhost is used to configure the loopback interface 
# when the system is booting. Do not change this entry. 
## 
127.0.0.1 localhost 
255.255.255.255 broadcasthost 
::1    localhost 
=> nil 

閱讀有關紅寶石以下概念將讓事情變得更清楚你:

  • 方面

  • self

  • include VS extend

相反的module_fuction你也可以實現與下面任一相同的結果:

module Hosts 
    extend Open3 
    extend self 

    def read 
    popen3("cat /etc/hosts") do |i,o,e,w| 
     puts o.read 
    end 
    end 
end 

而且

module Hosts 
    extend Open3 

    def self.read 
    popen3("cat /etc/hosts") do |i,o,e,w| 
     puts o.read 
    end 
    end 
end 
+0

啊,我一直在想着克這些線,但短缺。我將閱讀'擴展'。和'module_function'!非常感謝。 – spoovy

+0

@spoovy N/P :)你也可以用更少的選項達到同樣的效果。稍後將進行編輯(以防萬一您感興趣:)) –