I am trying to figure out how I can refactor my code below so that I can iterate through the array without using the "index1" and "index2" variables to keep track of my progress.
board.each do |cell|
diag1 << cell[index1]
diag2 << cell[index2]
index1 += 1
index2 -= 1
end
I tried using .each_with_index (see below), but I'm not sure how to increment my values for "i".
board.each_with_index do |cell, i|
diag1 << cell[i += 1]
diag2 << cell[i -= 1]
end
The array "board" is an n*n array of a tic-tac-to game that is at least 3x3 in size or larger and the block of code is supposed to check to see if there is a diagonal match. Thanks in advance!
Edit: Figured it out. Here is the working code snippet:
board.each_with_index do |cell, i|
diag1 << cell[i]
diag2 << cell[-(i +1)]
end
i + 1andi - 1? That will be broken, though, because you'll wrap around.board, what iscell(shouldn't it be ratherrow)? What is the input (board) and what is an expected output?boardmight be[["x", " ", " ", " "], [" ", "x", " ", " "], [" ", " ", "x", " "], [" ", " ", " ", "x"]]with the expected output ofdiag1to bexxxx, which is passed through another part of the code to confirm that it's a win. Here is the complete working code I have now for reference. gist.github.com/danielbonnell/6769fb41e2f5f4603fd9checkmethod will returntrueforOXXX?