1

如果有 2 个模块 - 模块Abc和模块Bcd和一个类 - 类Efg

现在我们想在一个实例中将模块包含Abc到类Efg中,并且需要Bcd在另一个实例中将模块包含到类 Efg 中,但不能同时包含两个模块。

是否可以在 Ruby 类中进行操作?

4

1 回答 1

2

如果我正确理解了您的问题,那么我认为您可以使用singleton_class仅包含一个特定类实例的模块:

inst1 = Efg.new
inst2 = Efg.new
inst3 = Efg.new

inst1.singleton_class.include Asd
inst2.singleton_class.include Bcd

现在inst1将拥有来自 的方法Asd并将inst2拥有来自 的方法Bcdinst3将没有任何方法。

于 2020-07-30T16:48:09.963 回答