考虑以下代码:在初始化程序中使用另一个对象的构造函数?
Campus = ImmutableStruct.new(:id, :name, :timezone) do
def hash; id end
end
Merchant = ImmutableStruct.new(:id, :name, :campus) do
def hash; id end
end
通知的hash
方法的重复。我想用新类ImmutableStructWithId
删除这个重复项。新课改将允许2行以上将被改写为:
Campus = ImmutableStructWithId.new(:id, :name, :timezone)
Merchant = ImmutableStructWithId.new(:id, :name, :campus)
如果红宝石的初始化工作就像工厂函数(他们不这样做),像下面是我想要的东西:
class ImmutableStructWithId
def initialize(*args)
ImmutableStruct.new(*args) do
def hash; id end
end
end
end
我知道上面是行不通的,因为初始化不回他们创建的对象,他们只是初始化它。但如果他们做工作的工厂功能,上面是我想要做的。
在红宝石中实现相同效果的正确方法是什么?
另外,我没有看到任何具体构造。你只是不想重复方法定义,不是吗? –
正确。最终,我想避免重复散列定义,并只使用一个特定的类来烘焙。 – Jonah
然后装饰者/委托人。 –