在Ruby中通过类访问实例变量而无需实例化新对象
问题描述:
我正在开发一个跳棋实现。我有这样(只显示相关部分)类:在Ruby中通过类访问实例变量而无需实例化新对象
class Game
attr_accessor :current_player
def initialize
@gui = Gui.new
@current_player = :red
end
end
,我有:
class Gui
def move_request
"#{Game.current_player.to_s.upcase} make move(x1, y1, x2, y2): "
end
end
我收到此错误:
gui.rb:8:in `move_request': undefined method `current_player' for Game:Class (NoMethodError)
我不想实例Gui
类中的新对象Game
,但我希望Gui
类可以访问current_player
实例变量状态。有关我应该做什么的想法?
答
实例变量在没有实例的情况下甚至不存在,因此您无法按照问题的方式访问实例变量。
你可能想要做像创建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
有迹象表明,这可以实现各种其他的方式,这是最好的取决于你的更广泛的使用情况。
似乎是一种误解:实例变量是实例状态(仅)的一部分,而不是类的一部分。只有在首先创建实例并设置了实例变量时才会意识到。所以你的问题对我没有意义... – mliebelt
@mliebelt我明白你在说什么,也许我可以用不同的方式说明:我有一个对象,gui,在我的Game类中声明,我怎么喂它.. 。只是意识到,我可以把它作为参数的方法,对不起......现在感觉很愚蠢...... –