- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
注意:此问题已发布在 Ruby-Forum没有得到答案
考虑这个模块:
module MM
def f
end
def self.g
end
module_function :f
end
f
和g
都是模块函数,可以这样调用
MM::f
MM::g
这只是品味问题,还是有充分的理由选择一种定义模块功能的方法?
我知道,当我将模块用作混合:
class CC
include MM
end
在这种情况下,f
也可以作为 CC
中的实例方法使用,而g
不是。然而,这在我看来并不特别有趣的功能:如果我设计一个模块用作混合到类,我不明白为什么我会使用 module_function。还有其他的吗我偏爱 self.FUNCTION
或 module_function
的原因定义模块函数时?
最佳答案
来自Doc :
module_function creates module functions for the named methods. These functions may be called with the module as a receiver, and also become available as instance methods to classes that mix in the module. Module functions are copies of the original, and so may be changed independently. The instance-method versions are made private. If used with no arguments, subsequently defined methods become module functions.
基本上,module_function 是一种使用模块方法而不将模块混入类的方法。
区别在于,如果你混入一个使用module_function
的模块,混入的方法将变成私有(private)实例方法(但它们将是公共(public)类方法声明模块)。因此,在您的示例中,当模块 MM
混入类 CC
时,f
成为私有(private)实例方法,但也可以用作: MM.f
.
当你有:
module MM
def f
end
module_function :f
end
然后您可以使用MM.f
,而无需将MM
模块混入CC
类中。但是,如果您不使用:
module_function :f
您始终可以使用以下方法将模块 MM
混合到 CC
类中:
class CC
include MM
end
并且可以使用方法f
作为CC
类对象的实例方法。
IMO,您真的没有更好的理由一般使用 module_function
。如果你想让你的模块方法作为类的实例方法,那么只需将模块包含到类中(将模块混合到类中),如上例所示。
而且,为了定义static
/utility
方法,您应该:
module MM
def self.g
end
end
或者,您甚至可以这样做:
module MM
extend self
def g
end
end
然后使用这样的方法:MM.g
不混入模块。所以,你真的不需要使用 module_function
。
关于ruby - 在 Ruby 中定义 module_function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32821237/
在 ruby 中,我知道可以使用 module_function 在模块中混合使用模块函数,如此处所示。我知道这是多么有用,因此您可以在不混入模块的情况下使用该函数。 module MyModul
据我了解,ruby 类除了具有能够实例化它的附加功能外,它们几乎与模块相同。由于 Class 继承自 Module,我假设每个类(类 Class 的对象)都可以访问 module_function,但
似乎如果您希望能够调用模块(/类)上的方法,那么您正在寻找一个单例...如果是这种情况,您最好使用类方法或Singleton mixin(不寻找其中一个“更好”的答案)。 我在使用 #module_f
我在 module_function 中看到了这个例子在 ruby 文档中。我不明白代码的后半部分,其中 Mod.one 返回旧的“这是一个”,而 c.one 返回更新后的“这是新的”。这是怎么发生的
注意:此问题已发布在 Ruby-Forum没有得到答案 考虑这个模块: module MM def f end def self.g end module_function :f
test_module.rb module MyModule def module_func_a puts "module_func_a invoked" priv
extend self 和 module_function 是实现它的两种 ruby 方法,因此您可以在模块上调用方法,如果包含该模块也可以调用它。 这些方式的最终结果有什么不同吗? 最佳答案 m
在阅读开源的 Ruby 代码和编写可维护性的代码经常遇到这两者的使用,那么他们两者的共同点和区别是什么呢? module_function Ruby 的 module 是 method 和 co
主要问题:在Ruby API docs对于 module_function 方法,我看到了以下代码示例: module Mod def one "This is one" end
我正在尝试覆盖这样定义的 Rails 辅助方法: class Foo module Bar def orig # orig code end alias o o
在 Ruby 中用 module_function 定义一个模块函数和用 self. 定义它一样吗?也就是说,它们是否都会导致实例方法和模块方法的创建? 最佳答案 没有。 module M1 de
我是一名优秀的程序员,十分优秀!