iteye_14321 2009-06-17 14:37
浏览 405
已采纳

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]

  • 写回答

5条回答 默认 最新

  • Hooopo 2009-06-17 21:03
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?