문제

I'm creating Conway's Game of Life with two classes: Board & Cell.

Board has access to Cell, but I'm not quite sure exactly how. Can't I place cell.board = self under Cell's initialize method? Why or why not? For sake of example, here's what I think are the relevant parts.

class Board
  #omitted variables & methods    

    def create_cell
        cell = Cell.new
        cell.board = self
    end
end

class Cell
    attr_accessor :board

    def initialize
    end
end    

Also, what does cell.board = self do exactly?

도움이 되었습니까?

해결책

There is an error in your code. Instead of cell = Class.new you should do cell = Cell.new. Yes you can pass the board (self) as a parameter in the Cell's constructor (initialize). In fact is more clean and functional in that way. Check out this code:

class Board
  def create_cell
    cell = Cell.new(self)
  end
end

class Cell
  attr_accessor :board

  def initialize board
    @board = board
  end
end

And then some examples of use.

$> b = Board.new
 # => #<Board:0x000001021c0298> 
$> c1 = b.create_cell
 # => #<Cell:0x000001021c27a0 @board=#<Board:0x000001021c0298>> 
$> c2 = b.create_cell
 # => #<Cell:0x000001021d4270 @board=#<Board:0x000001021c0298>> 
$> c2.board == c1.board
 # => true

As you can notice, either cell.board = self or using the constructor (initialize), is setting the current board instance into the created cell. So all these cells will point to that board.

다른 팁

cell.board = self sets the cell's board variable to the current board object (that is the board object on which you called the create_cell method.

If you put cell.board = self into Cell's initialize method, you'd get an error that cell is not defined in that scope. If you replaced it with @board = self, you'd set the board variable to the current Cell object (i.e. the one that's being created), not to a Board object. So that wouldn't be what you want.

Yes, you can. You can assign self to anything. You can't assign something else to self, but there's nothing wrong with assigning self to any other accessable variable or passing it to a method.

You could, for example, have written

class Board
  #omitted variables & methods    

    def create_cell
        cell = Class.new(self)
    end
end

class Cell
    attr_accessor :board

    def initialize(board)
      self.board = board
    end

end  

Also, what does cell.board = self do exactly?

It just passes a variable to the board= accessor. It's no different from passing any other variable.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top