直接上代码:
module M
# 一个普通的实例方法
def mul
@x * @y
end
module ClassMethods
# 一个类方法
def factory(x)
new(x, 2 * x)
end
end
#included方法是include方法的回调
def self.included(base)
#extend方法是给class添加类方法(include方法是添加实例方法)
base.extend ClassMethods
end
end
class P
include M
def initialize(x, y)
@x = x
@y = y
end
def sum
@x + @y
end
end
p1 = P.new(5, 15)
puts "#{p1.sum} #{p1.mul}"
#prints "20 75"
p2 = P.factory(10)
puts "#{p2.sum} #{p2.mul}"
#prints "30 200"
当P调用包含M时,ruby会自动调用M上的included(如果已定义)。它是include方法的回调。这用于将模块的类方法扩展到P上。详细文档:https://ruby-doc.org/core-2.2.0/Module.html#method-i-included
这篇博客探讨了在Ruby中如何通过module的included回调方法将类方法扩展到包括该模块的类上,提供了代码示例并引用了官方文档。
483

被折叠的 条评论
为什么被折叠?



