私は3つの単純なクラスCashRegister、BillとPositionを持っています。 CashRegisterはBillオブジェクトで構成され、BillオブジェクトはPositionオブジェクトで構成されます。それらは次のように実装されていますマーシャリングの助けを借りずにオブジェクトのディープコピーを作成するメソッド
class CashRegister
def initialize
@bills = []
end
def clone
#?
end
end
class Bill
def initialize(nr)
@nr = nr
@positions = []
end
def clone
#?
end
end
class Position
def initialize(product, price)
@product = product
@price = price
end
def clone
#?
end
end
これらのクラスのオブジェクトをディープコピーできるメソッドを作成する方法を教えてください。 Marshal.load(Marshal.dump(an_obj))
の使用は許可されていません。
編集:これまでのところ、私はこれを持っている:
class CashRegister
def initialize
@bills = []
end
def clone
@bills.map { |bill| bill.clone}
end
end
class Bill
def initialize(nr)
@nr = nr
@positions = []
end
def clone
cloned = super
cloned.positions = @positions.map{ |pos| pos.clone}
cloned
end
end
class Position
attr_reader :preis
# this method is given
def produkt
@produkt.clone()
end
def initialize(product, price)
@product = product
@price = price
end
def clone
cloned = super
cloned.product
cloned
end
end
クラスのポジションでcloneメソッドは、(なしコンパイルエラー)OKならないようです。しかし、クラスビルのエラーには「未定義のメソッドの位置=」というエラーがありますので、問題は行cloned.positions = @positions.map{ |pos| pos.clone}
にある必要がありますが、わかりません。cloned.positions
はそのように呼び出すことはできませんか?