Understanding Ruby Modules: Prepend vs. Include

Introduction:

  • Module is a collection of constants, methods, classes, and variables in a container.

  • Modules implement the mixin facility

      module Animal
        def sound
          puts 'animal sound'
        end
      end
    
  •     class Dog
          include Animal 
        end
    

    now we can access bark method

  •     Dog.new.sound # animal sound
    

    you can overwrite the sound method in Dog class

      class Dog
        include Animal 
    
       def sound
          puts 'bark'
        end
      end
    
      Dog.new.sound # bark
    

    what if we replace include to prepend

      class Dog
        prepend Animal 
    
       def sound
          puts 'bark'
        end
      end
    
      Dog.new.sound #animal sound, why I defined a sound method in a subclass?
    

    although we have overwritten the sound method in Dog class we called it returned the module method because we need to understand the ancestries chains

  • what are the ancestries chains?
    - the path of inheritance leading up to a given class or module

      class Dog
        include Animal 
    
       def sound
          puts 'bark'
        end
      end
    
      Dog.ancestors # [Dog Animal Object Kernel BasicObject]
    
      class Dog
        prepend Animal 
    
       def sound
          puts 'bark'
        end
      end
    
      Dog.ancestors # [Animal Dog Object Kernel BasicObject]
    

    using prepend makes Animal Method be executed over The dog method itself and no longer able to overwrite it

Conclusion:

  • Ruby modules are a powerful feature for organizing and reusing code in Ruby programs.

  • Understanding how to define, include, and extend modules is essential for effective Ruby programming and code design.

Additional Resources: