Reputation: 323
I'm creating a basic tic-tac-toe game to keep up my "Ruby chops." In the Game class, I've only gotten the generate_board
method to work using the code below. I can't seem to access the @board
instance variable directly. Can anyone explain why I'm having to call it as a method, and how to avoid this? Thank you!
class Board
def initialize
@board = (1..9).to_a
end
end
class Game
attr_accessor :board
def initialize
generate_board
end
def generate_board
new_board = Board.new
@board = new_board.board
end
end
Upvotes: 0
Views: 66
Reputation: 10398
On following Sagarpandya Answer You could write your code like this.
class Board
def initialize
@board = (1..9).to_a
end
end
class Game
attr_accessor :board
def initialize
generate_board
end
def generate_board
Board.new
end
end
p Game.new.generate_board
Upvotes: 0
Reputation: 9508
The instance variable @board
from the Board class is only accessible to other methods within the Board class. Since your method generate_board
is outside of the Board class and within a different class, the @board
instance variable from the Board class isn't accessible to the method in the Game class.
This in general is how instance variables work.
Upvotes: 1