我想弄清楚如何在Ruby中的類之間傳遞變量。我現在正在研究的例子是一個遊戲,玩家的健康,裝備等不斷變化,並且在場景之間傳遞,直到遊戲結束。以下是我迄今爲止:在Ruby中的類之間傳遞變量
class Player
def enter()
end
end
class MyPlayer < Player
def initialize()
dog_biscuits = false
end
end
class Scene
def enter()
end
end
class Entrance < Scene
def enter(player)
puts "You are in the entrance"
if player.dog_biscuits == false
puts "You don't have any biscuits."
end
end
end
player = MyPlayer.new
entrance = Entrance.new
entrance.enter(player)
每當我跑,我得到了以下錯誤消息:
entrance.rb:20:in `enter': undefined method `dog_biscuits' for #<MyPlayer:0x007fbfe2167f20> (NoMethodError)
我在OSX埃爾卡皮坦運行紅寶石2.2.3p173。
「傳球」位工作正常。你只是搞糟了'dog_biscuits'部分。在你的代碼中它是一個局部變量。你的意思是它是一個'attr_accessor'。谷歌了這個關鍵字的一些例子。 –
http://stackoverflow.com/a/4371458/125816 –