I am new to Ruby. A simple example, what I need:
class Animal
abstract eat()
class Cat < Animal
eat():
implementation
class Dog < Animal
eat():
implementation
In other words, the eat() method should be required for all the classes which extend Animal.
In JAVA I would just use an abstract class, but after doing some research I found that many people don’t use it in Ruby and mixin / modules are recommended instead.
However, I don’t understand, if modules can do more than just include an addition methods. To be exact, can modules set the requirements for classes which methods they must implement (if yes, an example would be appreciated)?
To sum up, what should I use in this case, when I want to be sure, that all classes of the same type have particular methods and implement them in their own way?
Ruby does not offer this functionality, no. You are responsible for making sure that your classes implement what they ought to implement.
Part of the reason that such functionality is impossible for Ruby is that Ruby classes can be reopened, and Ruby supports loading arbitrary code at runtime, so we can’t know whether a class implements a certain interface until we try to call it.
Supposing an
Animalmust have aneatmethod, and I do the following:By the end of that file, the
Catwill have itseatdefinition, because Ruby classes can reopened and modified multiple times. Should the code error out after the first definition becauseeatwasn’t defined yet? That implementation would hurt more than it would help, since reopening classes is common, even if this example is contrived. Should it error out once theeatmethod is called and does not exist, so we can be certain that it’s defined once we need it? Well, if the method were missing, that would happen, anyway. The interpreter can never know if another class definition is on the way, so it can never cut you off until the method is actually called.In short, superclasses simply cannot possibly require a method to be defined in Ruby, because the dynamic nature of classes contradict such a goal.
Sorry! This is a place where unit testing might come in handy, though, to ensure that your subclasses do what they’re supposed to be doing, anyway.