"包含"模块,但仍然无法调用该方法



为什么以下代码在下面给出错误?

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)

如果我使用完整路径IE Open3::popen3调用popen3,则可以使用。但是我已经include -ED,所以以为我不需要Open3::位?

谢谢

您已经定义了一种实例方法,但试图将其用作singleton方法。要使您想要的东西,您还必须使用extend Open3,而不是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

  • 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

最新更新