Search code examples
rubymultidimensional-arrayclass-instance-variables

Ruby: Nested Array behaving strangley as an Instance Variable


For our assignment, we were meant to create tic-tac-toe on a board of any size and accept an array as the input. I still am not fully grasping the attr_accessor module, and I'm pretty sure I used it incorrectly.

class Board
  attr_accessor :grid

  def initialize(grid = nil)
    if grid.nil?
      @grid = Array.new(3, Array.new(3, nil))
    else
      @grid = grid
    end
  end

  def place_mark(pos, mark)
    @grid[pos[0]][pos[1]] = mark
  end

 end

My main problem is even though it seems 'place_mark' should be placing the input in just one position. I get the following:

game.place_mark([0,0], :X) #=> [[:X, nil, nil], [:X, nil, nil], [:X, nil, nil]]

When I recreated this outside of a class, it worked just as I thought it should. What did I mess up?


Solution

  • There is nothing wrong with the Board class nor with attr_accessor. The initialization of the grid however does not work. @grid = Array.new(3, Array.new(3, nil)) is the culprit. The fourth code sample in the docs shows how it should be done, the text above it explains why OP's code behaves like it does. Every Ruby student gets trapped by this at least once.