可以调用模块的instance_method吗?

use*_*980 3 ruby

这是严格的理论.

module BleeTest
  def meth
    puts 'foo'
  end
end
Run Code Online (Sandbox Code Playgroud)

这段代码运行没有错误,但是有可能调用方法"meth"吗?

在我看来,"meth"是一个无法实例化的模块的实例方法.但那么为什么翻译允许这种结构呢?

Jör*_*tag 7

当然是.你可以混合BleeTest成一个对象:

o = Object.new
o.extend BleeTest

o.meth
# foo
Run Code Online (Sandbox Code Playgroud)

或者你可以混合BleeTest成一个类:

class C
  include BleeTest
end

o = C.new

o.meth
# foo
Run Code Online (Sandbox Code Playgroud)

实际上,第一种形式也可以用第二种形式表达:

o = Object.new

class << o
  include BleeTest
end

o.meth
# foo
Run Code Online (Sandbox Code Playgroud)

,毕竟整点模块在Ruby中:作为混入为了撰写的对象和类.