2012-09-11 24 views
2

我正在通过“学习Ruby困难的方法”,并且有关于调用对象内部方法的问题。我希望有人能够对此有所了解。Ruby - 调用对象内部的方法并使用.call()

The code是:

def play() 
    next_room = @start 

    while true 
    puts "\n--------" 
    room = method(next_room) 
    next_room = room.call() 
    end 
end 

我知道while循环中这种方法是什么使得在游戏继续其不同的领域。我的问题是,为什么room.call()必须先传递给next_room才能正常工作?为什么不只是做room.call()让游戏继续到下一个领域?

我自己测试了一下,我不明白为什么它不能这样工作。

回答

4

next_room是一个符号,它命名要调用的方法来确定下一个房间。如果我们看一下房间的方法之一,我们将看到这样的事情:

def central_corridor() 
    #... 
    if action == "shoot!" 
    #... 
    return :death 

所以,如果你有@start = :central_corridor然后开始在playnext_room将开始:central_corridor和第一个迭代器的while循环是这样这样的:

room = method(next_room) # Look up the method named central_corridor. 
next_room = room.call() # Call the central_corridor method to find the next room. 

假设你选择了拍摄时room.call()发生,那么:death将在next_room结束。然后通过循环的下一次迭代将通过room = method(next_room)查找death方法并执行它。

method方法用于将next_room中的符号转换为方法,然后调用该方法以查找接下来会发生什么。 接下来会发生什么部分来自room的返回值。所以每个房间都用一个方法表示,这些方法返回表示下一个房间的方法的名称。

+0

非常感谢您的深入解释。我明白这是如何工作的! –

0

这是我创建的简单代码。在print语句的帮助下,我们可以看到什么方法(next_room)和room.call()。

def printThis() 
    puts "thisss" 
end 

next_room = "printThis" 
print "next_room is: ", next_room; puts 


room = method(next_room) 
print "room is: ", room; puts 

room.call()