Screencast: Implementing each
Please read through this page; link to screencast at bottom . . .
In this screencast I’m going to talk about implementing each, and including the Enumerable module.
Let’s say that we have classes that represent rooms, floors, and houses. We might say that a house contains a number of floors, and a floor contains a number of rooms. In my house, there are two floors. On the first floor is an office and a TV room; on the second is another office, a living room, a dining room, a bathroom, two bedrooms, and a kitchen.
Now, let’s say as well that once we instantiate a House, we’d like some means to iterate through all of the rooms. This means that for a House my_house, we want to be able to call my_house.each. In other words, our final goal is to do something like this:
my_house.each { |room| puts room.name }
Once we have implemented each, we can now include the Enumerable module. With that, we can call methods such as #any? #map #find and all of the other very useful methods in Enumerable without any extra work.
Note that the any? method will be key to the assignment, especially for the ShyPlayer, because you are going to want to take the view that is passed to a Player, and write things like:
if view.any? { . . . some code goes here }
# do something
end
Remember, the ShyPlayer “goes shy” whenever there is any other player in its own view. A view is an instance of the World::Map class, so once you’ve implemented each on World::Map, and have included Enumerable, you will be able to write view.any? { . . . } from within your Player.
As a bonus, I’ll implement each_with_floor_and_room_numbers which should be very suggestive for each_with_coordinates. But for that, you’ll have to look at the screencast.
Implementing each and including Enumerable is discussed in Programming Ruby 1.9 at p. 80 in the print edition, p. 100 in the PDF. To see all of the methods you get after including Enumerable, see http://www.ruby-doc.org/ruby-1.9/classes/Enumerable.html
And here’s a discussion via Safari:
Here’s the code used in the demo: e168-implementing-each-jgn-1.0.000.zip
It would be DRYer to implement each_with_floor_and_room_numbers() first, then implement each() as
def each each_with_floor_and_room_numbers {|room, f, r| yield room} end@Ron Newman
Yep.
The example code is supposed to be suggestive for work one is doing for the assignment, and leaves opportunities for improvement . . .