So, what happens if you include Enumerable within a class of yours and forget to create an each method? If you have come to Ruby from the Java world, you might see a natural affinity between Ruby’s class hierarchy and Java’s (both have Object at the root). And you might also conclude that Ruby’s modules act in some way similar to Java’s interfaces. And so, you might expect that including the Enumerable module would check to see whether the each method is defined and throw an exception if it is not there. In Java, after all, interfaces force implementing classes to comply with their public list of methods; in essence, that acts as a contract with which the class must comply. You might reasonably expect Ruby to behave similarly. But let’s explore with an example.
For the sake of illustration, Listing 3 defines a class for bird watching that contains an internal hash of birds with counts of how many times they have been spotted. You might also notice this class declaration includes Enumerable but has not implemented the each function. Uh oh.
Listing 3. A Simple Bird-Watching Class
class BirdWatcher
include Enumerable
def initialize
@birds = {}
end
def saw_bird(bird)
if @birds[bird].nil?
@birds[bird] = 1
else
@birds[bird] += 1
end
end
end