这是Beginning Ruby的Dungeon示例:
class Dungeon
def add_room(reference, name, description, connections)
@rooms << Room.new(reference, name, description, connections,)
end
class Player
attr_accessor :name, :location
def initialize(player_name)
@name = player_name
end
end
def initialize(player_name)
@player = Player.new(player_name)
@rooms = []
end
end
my_dungeon = Dungeon.add_room(:largecave, "Large Cave", "a large cavernous cave", {:west => :smallcave})
my_dungeon = Dungeon.add_room(:smallcave, "Small Cave", "a small claustrophobic cave", {:east => :largecave})
此代码在Sublim Text 2中无错误地构建,直到我将其保存到HD上的文件中。一旦它保存到我的电脑,我就会从Sublime Text 2
中得到这个构建错误C:/Ruby193/bin/stephon.rb:18:in `<main>': undefined method `add_room' for Dungeon:Class (NoMethodError)
[Finished in 0.0s with exit code 1]
我在comm窗口中使用%PATH%
命令添加了此代码所在的目录和Ruby目录。没有变化。
任何帮助都将不胜感激。
答案 0 :(得分:0)
add_room
类上的Dungeon
方法是一种实例方法。这意味着,必须先创建类的新实例,然后才能在实例上调用该方法。
这样的事情应该有用(只要你在某处定义Room
类):
my_dungeon = Dungeon.new("Player 1")
my_dungeon.add_room(:largecave, "Large Cave", "a large cavernous cave", {:west => :smallcave})
my_dungeon.add_room(:smallcave, "Small Cave", "a small claustrophobic cave", {:east => :largecave})