Passionate Development From Journeyman to Master

A Thing or Two About Ruby Module

And so I am at Chapter 4 - Modules and program organisation of Well-Grounded Rubyist. When going through the chapter - the first impression that I’ve got is: Module is very similar to Java Interface.

At the surface it does seem like it. You can include multiple modules on your Ruby class - just like you can implement multiple interfaces in your Java class. Both also seems to be useful for implementing behavior that is shared among classes. So in the book, David gave an example of module “Stackability”.

But the similarities ends there.

Java Interface is a contract, if you “implement” an interface, you are promising that you will implement the methods in the interface in your class. Java will be unhappy if you break this contract. The interface itself does not contain any implementation details - it is simply a stub.

Ruby Module is not like this, methods in the module are fully working methods - I guess the closest thing that I can think of - module is like a library (I’ll see in few weeks time whether my understanding is correct).

Method lookup path is also interesting - if your class extends a class (which extends another class and so on) and includes a couple of modules - and just so happen every one of them have a method with the same name - which will get called first?

Rather that giving my own sub standard explanation, I would instead copy from this excellent blog post: Method Lookup by Gregory Brown

1) Methods defined in the object’s singleton class (i.e. the object itself) 2) Modules mixed into the singleton class in reverse order of inclusion 3) Methods defined by the object’s class 4) Modules included into the object’s class in reverse order of inclusion 5) Methods defined by the object’s superclass.

Checkout Gregory’s Ruby Mendicant University as well - while you are at it. This guy has done a lot for the Ruby community - ah, this is why I am really intrigued with Ruby and its community.

ruby on rails