0

I'm working on a checkers implementation. I have a class like (only relevant parts shown):

class Game
  attr_accessor :current_player

  def initialize
    @gui = Gui.new
    @current_player = :red
  end
end

and I have:

class Gui
  def move_request
    "#{Game.current_player.to_s.upcase} make move(x1, y1, x2, y2): "
  end
end

I am getting this error:

gui.rb:8:in `move_request': undefined method `current_player' for Game:Class (NoMethodError)

I don't want to instantiate a new Game object in the Gui class, but I want the Gui class to have access to the current_player instance variable state. Any thoughts on what I should do?

2
  • Seems like a misconception: instance variable is part of the state of the instance (only), not of the class. It is only realized, when first an instance is created, and the instance variable is set. So your question does not make sense to me ... Commented Nov 30, 2011 at 18:36
  • @mliebelt I understand what you're saying, maybe I can put it differently: I have an object, gui, declared in my Game class, how can I feed it...Just realized I can just place it as a parameter to the method, Sorry...feeling pretty stupid now... Commented Nov 30, 2011 at 18:44

1 Answer 1

2

An instance variable doesn't even exist without an instance, so you can't access one the way you're asking.

You probably want to do something like passing a reference to the game when creating the Gui:

class Game
  attr_accessor :current_player

  def initialize
    @gui = Gui.new(self)
    @current_player = :red
  end
end

class Gui
  def initialize(game)
    @game = game
  end

  def move_request
    "#{@game.current_player.to_s.upcase} make move(x1, y1, x2, y2): "
  end
end

There are various other ways that this could be achieved, which is best depends on your wider use case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.