oop - Copy a class so that the old class is not modified when I modify the new one in Ruby -
i have connectfour class , have method:
def apply_move!(column_number, symbol, row_number = 0)   # gravity logic   @board[row_number][column_number] = symbol end that modifies class in place.
i tried writing wrapper around returns board , not change original, function programming techniques used.
my attempt is:
def apply_move(column_number, symbol)   dummy = connectfour.new(@board)   dummy.apply_move!(column_number, symbol)   dummy end but trouble modifying dummy modifies original class itself! how modify dummy , dummy only?
more code , context
you interested in:
class cpuwinifpossible < player   def decide_move(board)     (0...6).find |move|       board.apply_move(move, self.symbol).is_won?(self.symbol)     end || (0...6).to_a.sample   end end here loop , execute apply_move board, can see definition above, apply_move should not change board, board shows 7 (+ 1) moves after code run: looks this:
player x: play (number 1 7) ?  2      o   o  oxoooo  winner o the constructor
class connectfour   attr_accessor :board     def initialize(board)     @board = board   end 
i think related current status of @board, if change connectfour#initialize looks following think should work
def initialize(board)   @board = board.dup end if using rails can use deep_dup
def initialize(board)   @board = board.deep_dup end 
Comments
Post a Comment