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