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. 

module A
    def greet
        puts "Greet from instance method"
    end
end

class B
    include A
end
a = B.new
a.greet

2. Extend

The extend keyword is used to bring all the methods inside the class and they can be used as class methods.

module A
    def greet
        puts "Greetings"
    end
end

class B
    extend A
end

B.greet

3. Prepend

When the module is prepended inside the class, all the methods become the instance methods of the class, but they take precedence over methods with the same name defined in the class itself.

module A
    def greet
        puts "Greetings from module"
    end
end


class B
    prepend A

    def greet
        puts "Greetings from class"
    end
end

B::new::greet

Comments