Learning Ruby, I'm creating a Battleship project and I have the following code as an instance method for a class "Board" I'm creating.
def hidden_ships_grid
hidden_s_grid = @grid.dup
hidden_s_grid.each_with_index do |sub_array, i|
sub_array.each_with_index do |el, j|
# position = [i, j]
hidden_s_grid[i][j] = :N if el == :S
end
end
end
Basically this method would create another instance of a @grid variable that would replace every :S symbol with a :N instead.
The RSPEC has two requirements: 1) "should return a 2D array representing the grid where every :S is replaced with an :N" and 2) "should not mutate the original @grid".
My problem is that my above code satisfies the first requirement, but it breaks the second requirement. Can someone please explain to me what is causing the original @grid file to be mutated? I've gone through the code 15 times over and I can't see where I rewrite or reassign the original @grid variable.
The "correct" solution provided to us uses ".map" which is fine, but I want to understand why this solution isn't working and ends up mutating the original @grid variable.
1) Board PART 2 #hidden_ships_grid should not mutate the original @grid
Failure/Error: expect(board.instance_variable_get(:@grid)).to eq([[:S, :N],[:X, :S]])
expected: [[:S, :N], [:X, :S]]
got: [[:N, :N], [:X, :N]]
(compared using ==)
Diff:
@@ -1,2 +1,2 @@
-[[:S, :N], [:X, :S]]
+[[:N, :N], [:X, :N]]