从类中返回值并获得无法解释的结果

时间:2013-07-14 22:49:40

标签: ruby oop learn-ruby-the-hard-way

我正在尝试制作一个小型游戏,你可以从一个房间到另一个房间,但是当我尝试返回下一个房间的值而不是我想要的字符串时,我得到的东西看起来像这样:

 #<Roseroom:0x007fe40984c778>

而不是

  "skullroom"

无论是使用$ global变量还是尝试返回“字符串”

,都会发生这种情况

也许我说这完全错了,所以如果你有任何建议也会受到赞赏。

这是我的代码,问题在于Roseroom类不会将“skullroom”发送回地图类(这是跑步者)。

$next_room = ''

class Engine

def initialize(stage)
    @stage = stage
    puts "succesfully initialized game"
    @map = Map.new(@stage)
end
end

class Map
def initialize(start)
    @start = start
    @rooms = {"roseroom" => method(:enterRose),
            "skullroom" => method(:enterSkull)
        }
    runner(@rooms, @start)
end

def runner(map, start)
    $next_room = start
    while true

        room = map[$next_room]
        puts $next_room
        $next_room = room.call()
        #method(:enterSkull).call() #This work if I call it directly

    end
end

def enterRose()
    @roseroom = Roseroom.new
end

def enterSkull()
    @skullroom = Skullroom.new
end

end

class Roseroom
def initialize
    puts "succesfully initialized roseroom"
    #$next_room = "skullroom"
    return "skullroom"

end

def exit

end
end

class Skullroom
def initialize
    puts "succesfully initialized skullroom"
    Process.exit(1)
end
end

game = Engine.new("roseroom")

如果有帮助,我可以在键盘上找到它: http://codepad.org/AlpkRIGb

谢谢!

1 个答案:

答案 0 :(得分:1)

Roseroom课程中没有任何东西会返回“头骨室”......你可能会觉得因为初始化的最后一行是return "skullroom",你会看到“头骨室”在Roseroom上返回。但事实并非如此......做Roseroom.new总会返回一个新的Roseroom对象。

你最好在Roseroom中定义一个返回“skullroom”

的next_room方法
class Roseroom
def next_room
  return "skullroom"
end

然后当你做...

def enterRose
  i_am_here = Roseroom.new 
  i_am_here.next_room
end

希望这有帮助。