Access to instance variables across classes in Ruby without instantiating a new object

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?

Answers


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.


Need Your Help

cp/rsync command with destination as symlink to a directory

linux bash shell unix scripting

I am working on a cPanel backup solution at the moment. We are now informed about this exploit.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.