本文介绍了是“扩展自我"吗?与“module_function"相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
extend self
和 module_function
是实现它的两种 ruby 方法,因此您可以在模块上调用方法,如果包含该模块也可以调用它.
extend self
and module_function
are two ruby ways to make it so you can call a method on a module and also call it if you include that module.
这些方式的最终结果有什么不同吗?
Are there any differences between the end results of those ways?
推荐答案
module_function
使给定的实例方法私有,然后复制它们并将它们作为公共方法放入模块的元类中.extend self
将所有实例方法添加到模块的单例中,保持它们的可见性不变.
module_function
makes the given instance methods private, then duplicates and puts them into the module's metaclass as public methods. extend self
adds all instance methods to the module's singleton, leaving their visibilities unchanged.
module M
extend self
def a; end
private
def b; end
end
module N
def c; end
private
def d; end
module_function :c, :d
end
class O
include M
include N
end
M.a
M.b # NoMethodError: private method `b' called for M:Module
N.c
N.d
O.new.a
O.new.b # NoMethodError: private method `b' called for O
O.new.c # NoMethodError: private method `c' called for O
O.new.d # NoMethodError: private method `d' called for O
这篇关于是“扩展自我"吗?与“module_function"相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!