In Ruby, both extend and include are used to mix in modules into classes, but they are used in different contexts and have different effects.
include: This is used to mix a module's methods as instance methods in a class. When you include a module in a class, the methods of that module become available to instances of the class, but not to the class itself.
module MyModule
def my_method
puts "This is a method from MyModule"
end
end
class MyClass
include MyModule
end
obj = MyClass.new
obj.my_method # This works
extend: This is used to mix a module's methods as class methods in a class. When you extend a module in a class, the methods of that module become available at the class level, but not to instances of the class.
module MyModule
def my_method
puts "This is a method from MyModule"
end
end
class MyClass
extend MyModule
end
MyClass.my_method # This works
obj = MyClass.new
# obj.my_method # This would raise a NoMethodError since my_method is not available to instances
So, in summary:
include is for mixing in instance methods.
extend is for mixing in class methods.
In many cases, you might see extend self used within a module, which effectively makes all its methods both class methods (accessible at the class level) and instance methods (accessible at the instance level).
In Ruby, both
extend
andinclude
are used to mix in modules into classes, but they are used in different contexts and have different effects.include
: This is used to mix a module's methods as instance methods in a class. When youinclude
a module in a class, the methods of that module become available to instances of the class, but not to the class itself.extend
: This is used to mix a module's methods as class methods in a class. When youextend
a module in a class, the methods of that module become available at the class level, but not to instances of the class.So, in summary:
include
is for mixing in instance methods.extend
is for mixing in class methods.In many cases, you might see
extend self
used within a module, which effectively makes all its methods both class methods (accessible at the class level) and instance methods (accessible at the instance level).