【问题标题】:Ruby excetend multiple class inside ModuleRuby 在 Module 中超过了多个类
【发布时间】:2021-06-17 18:51:45
【问题描述】:

你好有人可以帮助我吗?我需要在一个模块内扩展多个类,我尝试这种方式但不起作用。

module A
  def hello_A
    puts "hello from module A"
  end

end

module B
  extend A
  class C
    extend A
    def self.hello_B_C
      puts "Hello from Module B => Class C"
    end
  end

  class D
    def self.hello_B_D
      puts "Hello from Module B => Class D"
    end
  end
end

B::C.hello_B_C  => #Hello from Module B => Class C 
B::C.hello_A    => #Hello from module A
B::D.hello_A    => #undefined method `hello_A' for B::D:Class

我在模块 B 中扩展模块 A,并在模块 B 的所有子类中使用 hello_A

【问题讨论】:

    标签: ruby module


    【解决方案1】:

    B::D.hello_A 不起作用。

    当你有这个时:

    class B
      extend A
      class D
      end
    end
    

    D 类不与 B 共享任何功能。B::D 只不过是一个命名空间

    如果你这样做了

    class B
      extend A
      class D < self
      end
    end
    

    现在 D 继承了 B 的所有行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-07
      • 2013-10-28
      • 2020-12-06
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 2021-11-21
      相关资源
      最近更新 更多