ruby中include的问题

[code="java"]

module A
def m_test(options = {})
puts "A, #{self}"
end
end
module B
def m_test(options = {})
puts "B, #{self}"
end
end
module O
def invoke(m = nil, options = {})
n = "m_#{m}".to_sym
method = nil
method = self.method(n) if self.class.method_defined? n
method = self.method(:m_nil) if method.nil?
method.call(options)
end
def m_nil(options = {})
puts "NIL, #{self}"
end
end

class C
include O
def self.inc(mod = nil)
return false if mod.nil?
include mod
return true
end
end

1.times do
o = nil
o = C.new
o.invoke(:test, {:o => "off"})
o.class.inc A
o.invoke(:test, {:o => "on"})
o.class.inc B
o.invoke(:test, {:o => "on"})
o.class.inc A
o.invoke(:test, {:o => "on"})
end
[/code]

此代码运行后结果如下

NIL, #
A, #
B, #
B, #

请问,最后一次调用inc方法mix了A模块,为什么执行invoke却还是使用B模块中的m_test方法?

似乎曾经include过的模块就不能再被include了?
[b]问题补充:[/b]
那请问,怎样才能实现我需要的代码

或者说如何用变通的方法来实现多次include这样的效果
[b]问题补充:[/b]
其实我的目的是要在o对象生成之后反复覆盖o对象中的m_test这个方法

如果用load,似乎不好,还要用全局变量了

[code="ruby"]

file: m.rb

class C; def m_test; puts "C, #{self}"; end; end;
$o = C.new
$o.m_test
load 'a.rb'
$o.m_test

file: a.rb

def $o.m_test; puts "A, #{self}"; end;

[/code]

[code="ruby"]

module A
def m_test(options = {})
puts "A, #{self}"
end
end
module B
def m_test(options = {})
puts "B, #{self}"
end
end
module O
def invoke(m = nil, options = {})
n = "m_#{m}".to_sym
method = nil
method = self.method(n) if self.class.method_defined? n
method = self.method(:m_nil) if method.nil?
method.call(options)
end
def m_nil(options = {})
puts "NIL, #{self}"
end
end

class C
include O.dup
def self.inc(mod = nil)
return false if mod.nil?
include mod.dup
return true
end
end

1.times do
o = nil
o = C.new
o.invoke(:test, {:o => "off"})
o.class.inc A
o.invoke(:test, {:o => "on"})
o.class.inc B
o.invoke(:test, {:o => "on"})
o.class.inc A
o.invoke(:test, {:o => "on"})
end

[/code]
结果:
[code="ruby"]
NIL, #
A, #
B, #
A, #
[/code]

对,因为include加载的是模块,所以后面就不需要再次加载了

附:
Ruby中require,load,和include的区别
相同之处:三者均在kernel中定义的,均含有包含进某物之意。

不同之处:

1、requre,load用于文件,如.rb等等结尾的文件。

2、include则用于包含一个文件(.rb等结尾的文件)中的模块。

3、requre一般情况下用于加载库文件,而load则用于加载配置文件。

4、requre加载一次,load可加载多次。

用load不行吗?

lz 的代码看得我好痛苦…… 不要学 java 搞那么多花样

[code="ruby"]

整齐美观的三个 module …… 什么是代码之美?

module A

def test options = {}
puts "A, #{self}"

end

end

module B

def test options = {}
puts "B, #{self}"

end

end

module C
def test options = {}
puts "NIL, #{self}"
end
end

1.times do
o = Object.new
o.extend C
o.test :o => "off"
o.extend A
o.test :o => "on"
o.extend B
o.test :o => "on"
o.extend A.dup # o 不会被同一个人搞两次,所以要用复制人
o.test :o => "on"
end
[/code]

[quote]lz 的代码看得我好痛苦[/quote]
是啊,一看楼主的代码就知道楼主会多种语言..