简体   繁体   English

Ruby 超过模块内部的多个 class

[英]Ruby excetend multiple class inside Module

Hello someone can help me?你好有人可以帮助我吗? I need to extend multiple class inside one module, i try in this way but not work.我需要在一个模块内扩展多个 class,我尝试这种方式但不起作用。

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

I whold extend module A in Module B, and use hello_A in all subclass of Module B我在模块 B 中扩展模块 A,并在模块 B 的所有子类中使用 hello_A

B::D.hello_A wouldn't work. B::D.hello_A不起作用。

when you have this:当你有这个:

class B
  extend A
  class D
  end
end

The class D does not share any functionality with B. B::D is nothing but a namespace . class D 不与 B 共享任何功能。 B::D只不过是一个命名空间

If you instead did如果你改为

class B
  extend A
  class D < self
  end
end

Now D inherits all the behavior from B.现在 D 继承了 B 的所有行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM