The Difference Between include and extend in Ruby
written by Steven on August 02, 2012
To illustrate the difference I'm going to use a simple example of trying to get a Logger module into a class for use in the class.
Example 1 demonstrates include:
When you use include, the module's methods are added to the instances of the class. The log method is:
- Not available at the class level
- Available at the instance level
- Not available at the class level again
Example 2 demonstrates extend:
When you use extend, the module's methods are added to the class itself. The log method is:
- Available at the class level.
- Not available at the instance level.
- Available at the class level.
Example 3 demonstrates using both include and extend:
When you use both, the module's methods are added twice, both to the class and to the instances, so they are available anywhere.
You don't really want to do it this way. Not because it's bad, if you want the methods available to both you have to either add them to both or have the instance methods call the class methods, which is basically the same thing. So the reason you don't want to both include and extend is because your friends will think you rubyfu is weak. In an upcoming post I'll show you how to master this, so you can be strong.
Leave a Comment

Steven Bristol has written code for the past 20 years. He like green vegetables and kittens, oh and butterflies too. He loves to throw ninja stars at his enemies.
