如何从ruby实例方法返回一个新的self实例

时间:2021-09-26 22:28:39

I have a module which exists to be included in two similar classes. Some of the methods to be included in the module for identical use by both classes return a new instance.

我有一个模块,它存在于两个相似的类中。模块中包含的一些方法可供两个类使用相同的方法返回一个新实例。

But how to I encode in the module that the constructor for the containing class should be called?

但是如何在模块中编码应该调用包含类的构造函数?

A simplified example:

一个简化的例子:

module Point3D
  def initialize(x,y,z)
    @x = x
    @y = y
    @z = z
  end

  def * (scalar)
    <myclass>.new(@x * scalar, @y * scalar, @z * scalar)
  end
end

class Vertex
  include Point3D
end

class Vector
  include Point3D
end

So in the definition of * how would i call the constructor such that in the context of the Vertex class it returned a new Vertex and in the context of the Vector class it returned a new Vector without redeclaring all such methods in each class?

所以在*的定义中我将如何调用构造函数,使得在Vertex类的上下文中它返回一个新的顶点,并且在Vector类的上下文中它返回一个新的Vector而不重新声明每个类中的所有这些方法?

2 个解决方案

#1


13  

You can call 'class' method to get the class of obj.

您可以调用'class'方法来获取obj类。

For this case, it's

对于这种情况,它是

def * (scalar)
  self.class.new(...)
end

#2


3  

Use self.class to get the object of the class where the module is included.

使用self.class获取包含模块的类的对象。

#1


13  

You can call 'class' method to get the class of obj.

您可以调用'class'方法来获取obj类。

For this case, it's

对于这种情况,它是

def * (scalar)
  self.class.new(...)
end

#2


3  

Use self.class to get the object of the class where the module is included.

使用self.class获取包含模块的类的对象。