Ruby - 调用对象内部的方法并使用.call()

时间:2012-09-11 03:32:30

标签: ruby

我正在研究“学习Ruby The Hard Way”,并且有一个关于在对象中调用方法的问题。我希望有人可以对此有所了解。

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()让游戏继续到下一个区域?

我自己测试了这个,我不明白为什么它不会这样工作。

2 个答案:

答案 0 :(得分:4)

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

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

因此,如果您从@start = :central_corridor开始,那么在play中,next_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结束。然后,循环的下一次迭代将通过death查找room = method(next_room)方法并执行它。

method方法用于将next_room中的符号转换为方法,然后调用该方法以找出接下来发生的情况。 接下来发生的事情部分来自room的返回值。因此,每个房间都由一个方法表示,这些方法返回代表下一个房间的方法的名称。

答案 1 :(得分: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()
相关问题