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

时间:2017-04-21 09:07:28

标签: ruby include require

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

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)

如果我使用完整路径popen3呼叫Open3::popen3,则此功能正常。但我include - 编辑它,所以我认为我不需要Open3::位?

由于

1 个答案:

答案 0 :(得分:0)

您已定义了一个实例方法,但正在尝试将其用作单例方法。为了实现您想要的目标,您还必须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