0

I'm creating a command line connect four game where the board is created with a 2 dimensional array that represents the columns and rows. I use the following code to create the array

 @board = Array.new(6) {Array.new(7, " ")}

I'm creating a visual aspect to the connect four game using interpolation. Each element from each subarray in @board is represented as a "cell" using interpolation like below but it keeps giving me an 'undefined method `[]' for nil:NilClass' error.

puts "  #{@board[0][5]}  |  #{@board[1][5]}  |  #{@board[2][5]}  |  #{@board[3][5]}  |  #{@board[4][5]}  |  #{@board[5][5]}  |  #{@board[6][5]}"

That's just one row from the board. How can I access an element from the subarray so that it can display on my board using interpolation? The reason I want to use interpolation is that the values will change as the game goes on and they all start off as blank. If I remove one of the [] from the @board[][] callout it prints out a whole row in the "cell" which is not what I want. Any help is appreciated!

2
  • 5
    A small hint for troubleshooting problems like this. Remember this rule: "simplify and isolate". The error is in your puts statement. But you have no idea where in this string the error is. Therefore the correct procedure is to start to simplify the string in order to isolate where exactly the error comes from. When you do that, you should find the answer. Commented May 19, 2020 at 2:19
  • 2
    Getting the indices right can be hard when dealing with nested arrays. It might be easier to extract these array mechanics into a separate Board class, so you don't have to fiddle with the details in your higher-level game code. Commented May 19, 2020 at 10:00

1 Answer 1

4

You @board array includes 6 arrays with 7 blank strings in each of them. Array indexes start counting at 0 that means your outer array will return an inner array at the indexes 0 to 5

The last string interpolation in your code example looks like this: #{@board[6][5]}. The issue is that @board[6] does not exist and returns nil and nil does not respond to [5].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.