geekelo / dsa_practice

This repo is maintained just for the purpose of daily data structures and algorithm practice and proficiency
1 stars 0 forks source link

What is the difference between extend and include in Ruby? #4

Open geekelo opened 8 months ago

geekelo commented 8 months ago

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.

  1. 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
  2. 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:

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).