【问题标题】:'include'-ing a module, but still can't call the method'include'-ing 一个模块,但仍然不能调用该方法
【发布时间】:2017-09-18 04:55:44
【问题描述】:

为什么下面的代码会出现下面的错误?

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:: 位?

谢谢

【问题讨论】:

    标签: ruby include require


    【解决方案1】:

    您已经定义了一个实例方法,但正试图将其用作单例方法。为了使你想要的成为可能,你还必须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
    

    阅读 Ruby 中的以下概念会让你更清楚:

    • 上下文

    • self

    • includeextend

    除了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
    

    【讨论】:

    • 啊,我是按照这些思路思考的,但没能做到。我将阅读“扩展”。还有'module_function'!非常感谢。
    • @spoovy N/p :) 你也可以通过几个选项来达到同样的效果。稍后会编辑(以防您有兴趣:))
    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2012-12-23
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多