Methods to create deep copy of objects without the help of Marshal

Viewed 130

I have 3 simple classes CashRegister, Bill and Position. A CashRegister is composed of Bill objects and a Bill object is composed of Position objects. They're implemented as followed

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   

How do I create methods that can deep copy the objects of these classes. The use of Marshal.load(Marshal.dump(an_obj)) is not allowed.

Edit: So far I've got this:

    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   

The clone method in class Position seems to be ok (no compile error). But there is an error in the one in class Bill, it says "undefined method 'positions=', so the problem must be in the line cloned.positions = @positions.map{ |pos| pos.clone}. But I don't understand, can't we call cloned.positions like that?

3 Answers
Related