现在我们在 Person 类中使用 extend 关键字来调用模块,使用相关方法,并且打印出相关信息。
我们由 Person.introduce 和 Person.current_time 可以观察出来 extend 关键字的作用是为 Person 添加了2个类方法。
上面两个类调用的方法都报错了可以看出, include 和 extend 相反, include 是为类中添加的实例方法,而不是类方法。
prepend 和 include 同样都是为类中添加实例方法,但不同之处在于,引入模块后的方法链会有一点区别
我们先看看 include 的方法链
再看看 prepend 的
可以看出 FooModule 和 Person 的顺序有什么不同,那么具体不同体现在哪,接下来我们调用方法就可以看出区别了。
include
prepend
可以看到,如果使用 prepend 的话我们会优先去查找 FooModule 中的 introduce 方法(如果 FooModule 没有 introduce 方法话,会依次去祖先链的上一级去查找 introduce 方法),而 include 是优先在 Person 中去查找。