ruby特征类中的模包含

ruby特征类中的模包含,ruby,class,module,metaprogramming,Ruby,Class,Module,Metaprogramming,在我看来,例如,类作用域变成了单例类,也就是目标对象的本征类。因此,在对象的singleton类上创建的实例方法将成为该对象的singleton方法。我的意思是,以下两个代码片段会产生预期的结果 class TestClass; end 使用本征类 class TestClass class << self def class_method "class_method of TestClass" end end end 因此,我们可以调用

在我看来,例如,类作用域变成了单例类,也就是目标对象的本征类。因此,在对象的singleton类上创建的实例方法将成为该对象的singleton方法。我的意思是,以下两个代码片段会产生预期的结果

class TestClass; end
使用本征类

class TestClass
  class << self   
    def class_method
      "class_method of TestClass"
    end
  end
end
因此,我们可以调用TestClass.class_方法和TestClass.class_方法2并得到相应的结果。 现在让我们假设我们有一个模块TestModule

module TestModule
  def instance_method
    " instance_method from TestModule"
  end
end
现在,如果我们在eigen类中包含这个模块,那么我们可以访问实例_方法作为TestClass的类方法

class TestClass
  class << self   
    include TestModule
  end
end
当我试图调用TestClass.instance_方法时,我得到了以下错误

ArgumentError: wrong number of arguments(0 for 1)

有谁能解释一下问题是什么,以及背后的内在逻辑是什么。我非常感谢您提供的任何帮助。

这是因为如果您使用
include
,那么当前的类是什么并不重要,但是
self
指向什么(
include
是一种在
self
上调用的方法,如果您没有指定显式接收器),在您的示例中,
self
指向
TestClass
,因此
TestModule#instance_method
成为
TestClass
的实例方法,如下例所示:

class TestClass
end

module TestModule
  def test_method
    'test'
  end
end
TestClass.instance_eval { include TestModule }
TestClass.new.test_method
# => "test"

@pramod我的回答对你有帮助吗?你可以使用
instance\u eval
extend
来引入class方法:
TestClass.instance\u eval do;扩展测试模块;结束
,但这与只扩展TestClass.extend TestModule没有什么不同。
ArgumentError: wrong number of arguments(0 for 1)
class TestClass
end

module TestModule
  def test_method
    'test'
  end
end
TestClass.instance_eval { include TestModule }
TestClass.new.test_method
# => "test"