诗歌rails 之extend的用法
include是个语法(用1.class.methods.grep /include/ 不到),而extend是个方法(所有类或实例都有,因为是是根类Object的实例方法,见api:http://www.ruby-doc.org /core/classes/Object.html#M000335),用来给当前对象加载模块里的方法作为实例方法,如果当前对象是个类,那么就是成 为类方法,如果是实例,那么就是实例方法:
- irb(main):001:0> class C1
- irb(main):002:1> end
- => nil
- irb(main):003:0> module M1
- irb(main):004:1> def foo
- irb(main):005:2> puts "bar"
- irb(main):006:2> end
- irb(main):007:1> end
- => nil
- irb(main):008:0> C1.foo
- NoMethodError: undefined method `foo' for C1:Class
- from (irb):8
- irb(main):009:0> C1.extend M1
- => C1
- irb(main):010:0> C1.foo
- bar
- => nil
- irb(main):011:0> C1.new.foo
- NoMethodError: undefined method `foo' for #
- from (irb):11
- irb(main):012:0> C1.new.extend(M1).foo
- bar
- => nil
- irb(main):013:0>
莫愁前路无知己,天下无人不识君。