【发布时间】:2012-04-04 17:47:56
【问题描述】:
我正在尝试学习用 ruby 创建一个多类程序。我编写了一个引擎类和一些其他类,如城市、街道等,并且在将类名作为变量传递给其他类时遇到问题。下面的代码抛出错误:“City.rb:15:in 'intro': undefined local variable or method game' for # (NameError)”。我在某种程度上理解了这个问题,但我认为这个城市不需要知道任何事情 游戏对象,我认为它只需要获取它并将其传回即可。但显然我对如何在类之间传递变量(尤其是类名)有一个误解。我的设计有什么问题?
#Game.rb
require './City.rb'
class Engine
def initialize(city_name, street_name, budget)
@city = City.new(city_name)
@city.read_name()
play(@city, :intro, self)
end
def play(place, next_step, engine)
while true
next_step = place.method(next_step).call(place, next_step, engine)
end
end
end
game = Engine.new("Casablanca", "Costanza Boulvard", 200)
#City.rb
class City
def initialize(city_name)
@city_name = city_name
end
def read_name()
puts <<-READ_NAME
You are in a city called "#{@city_name}".
READ_NAME
end
def intro(place, next_step, engine)
puts "...."
game.play(@street, :enter, engine)
end
end
【问题讨论】:
-
我没有看到你在这里传递类名。
-
另外,修正你的命名。应该是
city.rb和game.rb(文件名 - snake_case,类名 - PascalCase)。 -
感谢您的提示。我试图在 game.rb#6 上将类名作为引擎传递为 self,在 game.rb#9 上作为变量引擎传递。这可能是我弄错的地方。你能给我一个可靠的例子,说明如何将一个类名传递给另一个类,完全不同于我的例子吗?
-
传递
self很好,但是在City.rb 中的intro方法中,我认为您应该使用engine.play而不是game.play。您也错过了将某些内容分配给@street... -
是否需要传递类或类名或类对象的实例?
标签: ruby variables parameter-passing