简体   繁体   English

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

[英]Ruby - Calling methods inside an object and using .call()

I'm working through "Learn Ruby The Hard Way", and have a question about calling a method inside an object. 我正在通过“学习Ruby的艰难方法”进行工作,并且对在对象内部调用方法有疑问。 I'm hoping someone can shed some light on this. 我希望有人能对此有所启发。

The code is: 代码是:

def play()
  next_room = @start

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

I know that the while loop in this method is what makes the game continue on to its different areas. 我知道这种方法的while循环是使游戏继续进行到不同区域的原因。 My question is, why does room.call() have to first be passed to next_room for it to work? 我的问题是,为什么必须首先将room.call()传递给next_room才能起作用? Why doesn't just doing room.call() make the game continue to the next area? 为什么不仅仅做room.call()使游戏继续到下一个区域?

I tested this out myself and I don't understand why it won't work this way. 我自己进行了测试,但我不明白为什么它不能以这种方式工作。

next_room is a symbol which names the method to be called to figure out which room is next. next_room是一个符号,它命名要用来确定下一个房间的方法。 If we look at one of the room methods, we'll see things like this: 如果我们查看其中一种房间方法,我们将看到如下内容:

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

So if you start with @start = :central_corridor then in play , next_room will start as :central_corridor and the first iterator of the while loop goes like this: 因此,如果您以@start = :central_corridor则在playnext_room将以:central_corridorwhile循环的第一个迭代器如下所示:

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.

Suppose you chose to shoot when room.call() happens, then :death will end up in next_room . 假设您选择在发生room.call()时进行拍摄,那么:death将最终在next_room中进行next_room Then the next iteration through the loop will look up the death method through room = method(next_room) and execute it. 然后,循环中的下一个迭代将通过room = method(next_room)查找death方法并执行该方法。

The method method is used to convert the symbol in next_room to a method, then that method is called to find out what happens next. method方法用于将next_room的符号转换为方法,然后调用该方法以找出下一步将发生的情况。 The what happens next part comes from the return value of room . 接下来发生的事情来自room的返回值。 So each room is represented by a method and those methods return the name of the method which represents the next room. 因此,每个房间都由一个方法表示,并且这些方法返回表示下一个房间的方法的名称。

This is a simple code I created. 这是我创建的简单代码。 With the help of print statements, we're able to visualize what method(next_room) and room.call() do. 借助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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM