为什么下面的代码会出现错误?
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,-ed,所以我觉得我不需要Open3::了?
谢谢
发布于 2017-04-21 09:10:51
您已经定义了一个实例方法,但正在尝试将其作为单例方法使用。为了使您想要的成为可能,您还必须使用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中的以下概念将使事情更加清晰:
selfinclude对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
endhttps://stackoverflow.com/questions/43538458
复制相似问题