0
0
RubyComparisonBeginner · 3 min read

Include vs Extend in Ruby: Key Differences and Usage

In Ruby, 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.

Aspectincludeextend
Adds methods toInstances of the classThe class or object itself
Method type addedInstance methodsSingleton (class) methods
Typical use caseSharing behavior among instancesAdding behavior to a single object or class
Effect on inheritance chainModule inserted in ancestors chainModule inserted as singleton class
Called onClass or moduleClass, 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:

ruby
module Greetings
  def greet
    "Hello from instance!"
  end
end

class Person
  include Greetings
end

person = Person.new
puts person.greet
Output
Hello from instance!
↔️

Extend Equivalent

Using extend to add class methods from the same module:

ruby
module Greetings
  def greet
    "Hello from class!"
  end
end

class Person
  extend Greetings
end

puts Person.greet
Output
Hello from class!
🎯

When 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.
Use 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.
Remember: include for instance-level, extend for class-level or object-level methods.