Alex E
Alex E

Reputation: 466

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. 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. My question is, why does room.call() have to first be passed to next_room for it to work? Why doesn't just doing room.call() make the game continue to the next area?

I tested this out myself and I don't understand why it won't work this way.

Upvotes: 2

Views: 1155

Answers (2)

mu is too short
mu is too short

Reputation: 434685

next_room is a symbol which names the method to be called to figure out which room is next. 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:

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. Then the next iteration through the loop will look up the death method through room = method(next_room) and execute it.

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. The what happens next part comes from the return value of room. So each room is represented by a method and those methods return the name of the method which represents the next room.

Upvotes: 4

ayjay
ayjay

Reputation: 177

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.

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()

Upvotes: 0

Related Questions