如果有 2 个模块 - 模块Abc
和模块Bcd
和一个类 - 类Efg
。
现在我们想在一个实例中将模块包含Abc
到类Efg
中,并且需要Bcd
在另一个实例中将模块包含到类 Efg 中,但不能同时包含两个模块。
是否可以在 Ruby 类中进行操作?
如果我正确理解了您的问题,那么我认为您可以使用singleton_class仅包含一个特定类实例的模块:
inst1 = Efg.new
inst2 = Efg.new
inst3 = Efg.new
inst1.singleton_class.include Asd
inst2.singleton_class.include Bcd
现在inst1
将拥有来自 的方法Asd
并将inst2
拥有来自 的方法Bcd
。inst3
将没有任何方法。