From: Alan Stern Date: 2001-10-06T06:01:37+09:00 Subject: [ruby-talk:22139] Ruby and multiple inheritance Ruby is widely known to support only single inheritance. But I'm going to try to show that Ruby actually supports multiple inheritance, albeit in disguise. Now literally, Ruby *is* a single-inheritance language, in the sense that classes can have only one class as a direct parent. However, classes can include arbitrarily many modules, and including a module is pretty much the same thing as having it as a parent. Furthermore, so far as I can tell, there is no major difference between a class and a module in Ruby -- except that classes can be instantiated and modules can't. (I'm not an expert, so somebody please correct me if this is wrong.) Modules can have instance methods, constants, and module methods, just like classes. Here's how to do multiple inheritance in the Ruby framework. Instead of defining a bunch of classes, making up some inheritance tree, define your classes as modules. So instead of having a class C, you will have a module MC. By including modules in other modules, you can effectively set up a multiple-inheritance network. That is, if you wanted to have class C derived from parents B1 and B2, you would simply have module MC include both modules MB1 and MB2. Finally, in order to make instances of MC, just define a dummy class MC_ that includes MC but has no other structure, and instantiate that. The reason people give for not using multiple inheritance is that it makes the inheritance hierarchy ambiguous (that's a quote from "Programming Ruby" by Thomas and Hunt). Certainly with multiple parent classes, the meaning of the superclass method becomes a bit fuzzy, but that isn't a real problem. The real problem is: what happens when more than one parent contains a definition for the same method? Which one should be used in the child class? In the Ruby-style version of multiple inheritance described above, the answer is simple. Although a module can have multiple parents (that is, can include multiple parent modules), the parents are not equivalent -- they get included in some definite order. If a method is defined in more than one of the parent modules, Ruby will use the version defined in the most-recently included module. I hope this has managed to muddy the distinction between single- and multiple-inheritance in Ruby, and that it will stimulate some discussion. Alan Stern