对象 Ruby 中的模块方法

Module methods in Object Ruby

我无法理解 Ruby 中的全局可见区域,因此,我知道您不能在自己的 class 中使用模块方法,例如:

module Mod
   def self.meth
      “module method”
   end
end

class Klass
   include Mod
end

p Klass.meth

# Error

但是当我知道你可以做这样的事情时:

include Math

p sin 2
#0.909....

我很困惑,因为我认为你不能在任何 class 中使用模块方法而不调用方法名称。我也有一个假设,Math 模块有实例方法,比如 Kernel,但不幸的是,没有。现在我怀疑,我是否正确理解扩展和包含这样的方法,所以,请你向我解释一下这件事,如果我们将包含更改为扩展

会发生什么

你遇到了module_function的怪事:https://apidock.com/ruby/Module/module_function/

module Foo
  def foo # this is (irb) 2
  end
end

Foo.singleton_methods #=> []
Foo.instance_methods #=> [:foo]
Foo.instance_method(:foo).source_location #=> ["(irb)", 2]

module Foo
  module_function :foo # this is (irb) 9
end

Foo.singleton_methods #=> [:foo]
Foo.singleton_method(:foo).source_location #=> ["(irb)", 2]
Foo.instance_methods #=> []
Foo.private_instance_methods #=> [:foo]
Foo.instance_method(:foo).source_location #=> ["(irb)", 2]

因此,module_function 采用模块的实例方法,将其设为私有并将其复制到单例中 class。

module_function也可以不带方法名使用,有点像private方法,修改以后添加到这个模块的所有方法。

Math 是一个完整的 module_function 模块,这意味着方法被定义为单例和私有实例方法,这就是为什么您可以两种方式使用它的原因。