Ruby:在类外部和类内部编写扩展有什么区别

时间:2014-08-16 19:43:40

标签: ruby module mixins

我在网址In Ruby or Rails, why is "include" sometimes inside the class and sometimes outside the class?读到了这个问题。根据这个问题的答案,我希望类print2的方法Calculation应该可以被AdditionABc访问。但是我收到错误{{{ 1}} print2'for Addition:Class(NoMethodError)`

undefined method

请解释为什么会出现这个错误?

由于

2 个答案:

答案 0 :(得分:2)

extend的接收者应该是每个类,因此您需要Addition.extend CalculationAbc.extend Calculation(在类定义之后)。分号不是必需的。

module D
  def dog
    puts "woof"
  end
end

class A; end
A.extend D
A.dog #=> "woof"

class B; end
B.extend D
B.dog #=> "woof"

答案 1 :(得分:1)

我的预感是你的extend(在任何一类之外)扩展了主要的本征类。主要是您当前运行时环境的Object实例。 Eigenclass是一个对象的类,其唯一的实例是给定的对象。 Ruby中的每个对象都有一个Eigenclass。没有什么继承自Eigenclass。因此,extend不会继承到任何其他类。

相关问题