Include, Extend and Prepend in Ruby | Mixins in Ruby
In Ruby, include, extend, and prepend keywords are used to mix modules in class. In Ruby multiple inheritance is not supported, modules are mixed with classes to achieve this functionality. This is also known as Mixins.
This approach not only provides code reuse, and modularity but also promotes a more flexible codebase. The use of mixins enhances code readability and maintainability. In Ruby, include, extend, and prepend are three different ways to mix functionality from modules into classes. Each has its own distinct purpose and behavior:
1. Include
Include keyword is used to bring all methods inside the class. This means all the methods are included as instance methods. They can be called with an object of that class.
def greet
puts "Greet from instance method"
end
end
class B
include A
end
a = B.new
a.greet
2. Extend
3. Prepend
Comments
Post a Comment