Search code examples
javascriptrubyfunctionglobal-variablesstoring-data

Ruby trying to store array elements when reiterating through functions


I am attempting to make a tic tac toe game. I have a good idea of where to go, and I know what the problem is, but I am not sure how to fix it. When I create a function, I establish variables for that function. i = 0, row1 = [], but when I am reiterating through the functions, every time the function gets called again, row1 is back to empty because of the initial row1 = [], and the counter I want to use, i = 0, goes back to 0 every time because the beginning of the function I am setting my variables. I think the solution may be to make the variable global, and set it out of the function, but I am not sure how to do that. But if anyone has any suggestions it would be greatly appreciated. Here is the problem code.

def row1(player)
    row1 = []
    row1[player - 1] = "X"

    puts "#{row1}"

end

def choosespot_x

    puts "X -- Choose a spot"
    move = gets.chomp.to_i
    if move <= 3
        row1(move)
    end

choosespot_x

end

Solution

  • Global variables are prefixed by $ and are generally a bad idea in Ruby.

    Instance variables, prefixed by @, can also do what you want; on top-level, they behave pretty much the same as globals, but in classes or modules they are nicely isolated.

    So the best way would be to make a class; create your variable (say, @row1) in the initialize method, and then you will be able to just use it in choosespot_x method.

    EDIT: The way I'd do it...

    module TicTacToe
      class Board
        def initialize
          @board = Array.new(9)
        end
    
        def [](y, x)
          @board[x + y * 3 - 4]
        end
    
        def []=(y, x, value)
          @board[x + y * 3 - 4] = value
        end
      end
    end
    
    board = TicTacToe::Board.new
    board[1, 3] = :white
    board[3, 2] = :black
    board[1, 3]
    # => :white
    board[1, 1]
    # => nil