首先定义一个Module:
module Foo
def bar
puts "foo";
end
end
然后我们把这个模块混入到对象中去:
class Demo
include Foo
end
如上编码后,模块中的实例方法就会被混入到对象中:
d=Demo.new
d.bar
会输出foo字样。
下面我们重新定义一下Demo类:
class Demo
extend Foo
end
这个时候如果你得到的就是静态调用:
Demo.bar
会输出foo字样。
下面我们再来重新定义一下Demo类:
class Demo
def bar
puts "demo"
end
end
然后使用extend方法调用:
d=Demo.new
d.extend(Foo)
d.bar
会输出foo字样。
下面我们再来重新定义一下Demo类:
class Demo
include Foo
def bar
puts "demo"
end
end
然后使用extend方法调用:
d=Demo.new
d.extend(Foo)
d.bar
module Foo
def bar
puts "foo";
end
end
然后我们把这个模块混入到对象中去:
class Demo
include Foo
end
如上编码后,模块中的实例方法就会被混入到对象中:
d=Demo.new
d.bar
会输出foo字样。
下面我们重新定义一下Demo类:
class Demo
extend Foo
end
这个时候如果你得到的就是静态调用:
Demo.bar
会输出foo字样。
下面我们再来重新定义一下Demo类:
class Demo
def bar
puts "demo"
end
end
然后使用extend方法调用:
d=Demo.new
d.extend(Foo)
d.bar
会输出foo字样。
下面我们再来重新定义一下Demo类:
class Demo
include Foo
def bar
puts "demo"
end
end
然后使用extend方法调用:
d=Demo.new
d.extend(Foo)
d.bar
会输出demo字样。
include主要用来将一个模块插入(mix)到一个类或者其它模块。
extend 用来在一个对象(object,或者说是instance)中引入一个模块,这个类从而也具备了这个模块的方法。
通常引用模块有以下3种情况:
1.在类定义中引入模块,使模块中的方法成为类的实例方法
这种情况是最常见的
直接 include <module name>即可
2.在类定义中引入模块,使模块中的方法成为类的类方法
这种情况也是比较常见的
直接 extend <module name>即可
3.在类定义中引入模块,既希望引入实例方法,也希望引入类方法
这个时候需要使用 include,
但是在模块中对类方法的定义有不同,定义出现在 方法
def self.included(c) ... end 中
require和load不同,它只加载文件一次,即在第一次执行到require时载入,以后碰到require同一文件时自动忽略,已经被加载的文件保存在$”中。另外,require还可以用来加载二进制格式的库。Require可以使用绝对路径或相对路径,如果使用了相对路径,那么系统会在$:变量包含的目录中搜寻。Require和load的另一个不同是当包含文件是Ruby代码时,require可以不加后缀名。Require将当前所有加载的文件保存在$"变量中。