Ex 47 confused with assert_equal in test_map function

here is the code that confuses me:

as you can see, 1st we make 3 instance of the Room class (start, west & down)
start = Room("Start", "You can go west and down a hole.")
west = Room("Trees", "There are trees here, you can go east.")
down = Room("Dungeon", "It's dark down here, you can go up.")

than we add paths using key-value pairs. each key leads to a value of an instance from Room
start.add_paths({'west': west, 'down': down})
west.add_paths({'east': start})
down.add_paths({'up': start})

finally we test the maps of those rooms using assert_equal to make sure the actual object gives us our desire object
assert_equal(start.go('west').go('east'), start)
assert_equal(start.go('down').go('up'), start)

I don’t understand the last 2 lines with assert_equal. The actual object here will be the instances of Room, west and start (west derived from the key 'west' and start derived from the key 'east'), while the desired object is only the instance starts. Thus, west and start, the actual objects don’t match start the desired object.

As a result shouldn’t this code this code fail the assert_equal test than, since the actual and desired object of assert_equal don’t match?

Ah, @zkg22 that’s an easy one. What if you did that like this:

west = start.go('west')
east = west.go('east')
assert_equal(east, start)

Remember that .go return the next Room, which also has .go. So, what I’ve written here is the same as that first line you’re confused about. The only thing you’re missing is you don’t have to assign the return value to some variable all the time, you can “chain the dots”. In this case, I do start.go().go() which is just taking the return of the first call to go and calling .go on that. If you look at the code I just typed up here, that’s west. Then the next .go is west.go.

You could, in theory, do this forever as long as the .go() method kept returning some instance of Room.

1 Like

ahh I see now. Thanks for clarifying, I honestly did not make that connection.

So, the return value allows us to transition to the next direction by retaining the previously retrieved value from the initial .go() method as an instance to call the upcoming .go() method.

I’m such a noob, haha. I knew that but just missed the connection.

much thanks

Yep, as long as you keep operating on the results they stay around. They basically live for the whole time that line is active unless you save it to a variable or put it somewhere to store it.

1 Like