[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]