Ruby中类似模块的结构包含?
因此,我尝试了以下代码:Ruby中类似模块的结构包含?,ruby,struct,module,Ruby,Struct,Module,因此,我尝试了以下代码: ComplicatedClass module InternalObjects InternalThing = Struct.new(:name, :description) end end class ComplicatedClass module Operations def operate_on_object InternalThing.new end end end class ComplicatedCla
ComplicatedClass
module InternalObjects
InternalThing = Struct.new(:name, :description)
end
end
class ComplicatedClass
module Operations
def operate_on_object
InternalThing.new
end
end
end
class ComplicatedClass
include InternalObjects
include Operations
def other_operate_on_object
InternalThing.new
end
end
然后使用cc=complexdclass.new
,cc.other\u operate\u on\u object
工作正常,但调用cc.operate\u on\u object
会导致名称错误:未初始化常量complexdclass::Operations::InternalThing
显然,我可以选择不使用InternalObjects
模块,只在复杂类中定义结构:
class ComplicatedClass
InternalThing = Struct.new(:name, :description)
include Operations
def other_operate_on_object
InternalThing.new
end
end
并且没有问题,但是在其他地方重用相同的结构是令人讨厌的(并且可能会导致在初始化例程中进行元编程作为解决方法)
同样,我也可以在操作模块中为new
调用命名名称(complementclass::InternalThing.new
),但从代码重用的角度来看,这是极不明智的
- 有没有一种方法可以在模块中定义一个结构,这样您就可以在类中包含该模块,然后让其他模块中包含的方法能够使用该结构李>
- 即使你可以,这是个坏主意吗李>
- 如果我有一些在整个应用程序中以一定频率重用的结构,有没有合适的方法以类似模块的方式定义它们?还是我应该采取不同的方法李>
- 元编程真的是我最好的选择吗李>
- 或者即使他们非常非常
非常非常愚蠢的东西我应该把它们变成自己的吗
全面课程
从代码重用的角度来看,给new
调用命名是不明智的。这就是常量查找的工作原理。即使您在复杂类::操作
名称空间中定义了InternalThing
,您仍然需要从#operate_on_object
中说出self.class::InternalThing
,因为它是一个实例方法。即使包含/扩展了常量的父模块,常量也不会共享。实际上,有时建议使用静态方法/名称空间,因为它更容易重构(当然,有时也建议使用相反的方法)。我认为在某种程度上,类常量并没有真正注册,而“噢,duh”时刻让事情变得更清楚了。谢谢