Section 3. Duck Typing

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. ...

Get Rubyisms in Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.