在Ruby语言中,我理解了extend
的基本思想。然而,在这段代码中发生了什么?具体地说,extend
做了什么?这只是一种将实例方法转换为类方法的便捷方法吗?为什么要这样做,而不是从一开始就指定类方法?
module Rake
include Test::Unit::Assertions
def run_tests # etc.
end
# what does the next line do?
extend self
end
发布于 2009-11-14 11:57:49
这是一种将实例方法转换为类方法的便捷方法。但您也可以将其用作more efficient singleton。
发布于 2009-11-14 11:52:10
在模块中,self本身就是模块类。举个例子
puts self
会返回瑞克所以,
extend self
基本上是让Rake中定义的实例方法对它可用,所以你可以这样做
Rake.run_tests
发布于 2012-07-23 15:10:32
对我来说,将extend
看作单例类(也称为元或本征类)中的include
总是很有帮助的。
您可能知道在singleton类中定义的方法基本上都是类方法:
module A
class << self
def x
puts 'x'
end
end
end
A.x #=> 'x'
现在我们知道了,extend
将include
单例类内部模块中的方法,从而将它们公开为类方法:
module A
class << self
include A
def x
puts 'x'
end
end
def y
puts 'y'
end
end
A.x #=> 'x'
A.y #=> 'y'
https://stackoverflow.com/questions/1733124
复制相似问题