Include vs Extend in Ruby: Key Differences and Usage
include adds a module's methods as instance methods to a class, while extend adds them as class methods. Use include when you want objects to use the module's methods, and extend when you want the class itself to have those methods.Quick Comparison
This table summarizes the main differences between include and extend in Ruby.
| Aspect | include | extend |
|---|---|---|
| Adds methods to | Instances of the class | The class or object itself |
| Method type added | Instance methods | Singleton (class) methods |
| Typical use case | Sharing behavior among instances | Adding behavior to a single object or class |
| Effect on inheritance chain | Module inserted in ancestors chain | Module inserted as singleton class |
| Called on | Class or module | Class, module, or object |
Key Differences
include mixes in a module's methods as instance methods. This means every object created from the class can call those methods. The module is inserted into the class's inheritance chain, so Ruby looks there when resolving method calls.
On the other hand, extend adds the module's methods as singleton methods to the receiver. If used in a class, it adds class methods. If used on an object, it adds methods only to that object. This does not affect instances of the class.
In short, include is for sharing behavior with instances, while extend is for adding behavior to the class or a specific object itself.
Code Comparison
Using include to add instance methods from a module:
module Greetings
def greet
"Hello from instance!"
end
end
class Person
include Greetings
end
person = Person.new
puts person.greetExtend Equivalent
Using extend to add class methods from the same module:
module Greetings
def greet
"Hello from class!"
end
end
class Person
extend Greetings
end
puts Person.greetWhen to Use Which
Choose include when you want all instances of a class to share common behavior defined in a module as instance methods. Choose extend when you want to add methods to a single object or to the class itself as class methods. For example, use include for reusable instance features and extend for utility or helper methods at the class level.
Key Takeaways
include adds module methods as instance methods to a class.extend adds module methods as class (singleton) methods to a class or object.include to share behavior with instances, extend to add behavior to the class or a single object.include affects the inheritance chain; extend does not.include for instance-level, extend for class-level or object-level methods.