If someone has the time, could someone clarify how 2 methods work? The methods are the 2 indexing through the grid. I understand the bottom one is a
setter while the top is a
getter but why do I need the
getter in order to use the
setter? I tried to set a position on the grid to a symbol without the
getter defined and it didn’t work. Why is that?
Also, in my
initialize method, why does
class need to be attached to
self in order to call
default_grid? This question isn’t too important because I can live with “that’s the way it is” but if there is a deeper understanding I can gain, that would be great
def initialize(grid = self.class.default_grid)
@grid = grid
def (pos) <<<<< Getter
row, col = pos
def =(pos, sym) <<<<<<Setter
x, y = pos
grid[x][y] = sym
I can’t speak to why the
setter as written would need your
getter method, we’d probably need more info to replicate that and see what’s going on.
As to your other question, it has to do with what the method is defined for. We define factory methods with the
self keyword in them to remind us what they are. They’re methods for building instances or important pieces of instances and they’re defined on the class, rather than the instance. We use one in mastermind called
parse in order to generate an instance of code, and we use one in battleship to auto-generate a grid we can use for our board.
This is the error I get when I comment out the getter.
This is what happens when I comment out the Setter
This is the tests that are run
Ah, I see now. I had initially thought you were running the code and it was failing. The error here is that the test for #attack uses both methods. It uses the setter to place the mark when it calls attack and the getter to take a look at it on the expect line. When either one is missing, the test fails.