为什么返回方法的符号而不是只调用方法? (Ruby the Hard Way Ex43)

时间:2022-04-05 19:14:12

As i study this lesson, I see the following blocks and methods.

在我学习本课程时,我看到了以下块和方法。

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

def death()
  puts "you die"
  Process.exit(1)
end

def central_corridor()
  puts "He's about to pull a weapon to blast you."
  prompt(); action = gets.chomp()

  if action == "shoot!"
    puts "Your laser misses him entirely."
    return :death

So returning :death clearly launches the death() method, but why is this better than simply calling death() outright ?

所以返回:死亡显然会启动death()方法,但为什么这比简单地直接调用death()更好?

Could not this game go through its entire range of "rooms" just by "calling" other room methods?

难道这个游戏难道只是通过“呼叫”其他房间方法来完成整个“房间”范围吗?

Is the purpose simply to teach us about the method method?

目的只是为了教我们方法方法吗?

Thanks

1 个解决方案

#1


1  

The program is designed so that each "room" has a method, and the protocol when calling a room method is to do whatever is appropriate for that room, then return the symbol of the next room. This way the instance of Game can keep track of which room is current, which room is next, and call the appropriate method. It's a reasonable design decision that may seem like overkill at this small scale, but it would make sense if the game were to grow.

该程序的设计使每个“房间”都有一个方法,调用房间方法时的协议是做适合该房间的任何事情,然后返回下一个房间的符号。这样,游戏的实例可以跟踪哪个房间是当前的,下一个房间,并调用适当的方法。这是一个合理的设计决定,在这么小的范围内可能看起来有点过分,但如果游戏要增长则会有意义。

#1


1  

The program is designed so that each "room" has a method, and the protocol when calling a room method is to do whatever is appropriate for that room, then return the symbol of the next room. This way the instance of Game can keep track of which room is current, which room is next, and call the appropriate method. It's a reasonable design decision that may seem like overkill at this small scale, but it would make sense if the game were to grow.

该程序的设计使每个“房间”都有一个方法,调用房间方法时的协议是做适合该房间的任何事情,然后返回下一个房间的符号。这样,游戏的实例可以跟踪哪个房间是当前的,下一个房间,并调用适当的方法。这是一个合理的设计决定,在这么小的范围内可能看起来有点过分,但如果游戏要增长则会有意义。