


class A




这样A的对象就多了一个hello方法。也许这样满足你的需求,可是你注意到没有,you've made a change to class A.
所以高手Jay Field建议我们,不要这么做。
he said : Use modules instead of adding behavior directly.
class B
end
module Bextend
def hello
p “hello b”
end
end
B.send :include,Bextend
B.new.hello
#=> “hello b”
B.ancestors
#=> [B, Bextend, Object, Kernel]
如果你直接opening class去添加你的行为,会增加耦合性(个人理解,欢迎高手指点), 而使用module,会更加灵活。
灵活在哪呢?
好,当你使用opening class的方式添加了一个方法:





那么现在给你个任务:change the hello method to include the original behavior and add a name.
你怎么做呢 ? 只能这么做了吧:






但是,如果你使用module来代替opening class的方式定义方法:









Object.ancestors

你要完成上面的任务只需要:









hello("Ali")



上面的例子, 如果你想调用老的hello方法,只需要个super就够了。