Ruby使用include和extend来对class做补充。
假设有一个module:
module Person def about_me puts "This is about me." end end
?
1, include <module name>
? 1.1 使模块的方法变成类的实例方法:
class Student include Person end student = Student.new student.about_me # puts "This is about me." Student.about_me # 没有定义此方法,抛出异常。
? ?1.2 如何要让 Student 可以直接调用include module的方法,可以在?def self.included(c) ... end 实现,比如
?
module Person def about_me puts "This is about me." end def self.included(c) def c.call_me puts "This is class me" end end end
? ?Student.call_me即可直接调用。
?
2,?extend?<module name>是直接变成类的类方法 ,相当于class << self.?
?
参考资料:?http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby