Sobes.tech
Junior

What are modules used for in Ruby?

sobes.tech AI

Answer from AI

Modules in Ruby are used for two main purposes:

  1. Namespaces: Organizing code to prevent name conflicts. They allow grouping related classes, methods, and constants under a single name. This helps avoid situations where two different classes or methods have the same name.

    # module_for_namespace.rb
    module MyFramework
      class Validator
        def validate(data)
          # validation logic
        end
      end
    end
    
    # another_file.rb
    # To use Validator from MyFramework:
    validator = MyFramework::Validator.new
    validator.validate("some data")
    
  2. Mixins: A mechanism for sharing functionality (methods) among multiple classes without using classical inheritance. Modules are included in classes using include or prepend.

    • include: Module methods become available in class instances and can be overridden in the class itself. Method lookup order: current class, included module, superclasses.
    • prepend: Inserts the module into the inheritance chain before the class. Module methods have priority over class methods.

    Example of using include:

    # mixin_module.rb
    module Loggable
      def log(message)
        puts "[LOG] #{message}"
      end
    end
    
    # class_using_mixin.rb
    class MyClass
      include Loggable # Including Loggable module
    
      def process_data
        log("Processing data...") # Using method from module
        # other logic
      end
    end
    
    obj = MyClass.new
    obj.process_data
    

    Example of using prepend:

    # mixin_module.rb
    module MyPrependedModule
      def greet
        puts "Hello from module!"
      end
    end
    
    # class_with_prepend.rb
    class MyPrependClass
      prepend MyPrependedModule # Module will be before class in inheritance chain
    
      def greet
        puts "Hello from class!"
      end
    end
    
    obj = MyPrependClass.new
    obj.greet # Will output "Hello from module!" because module method has priority
    

Modules cannot be instantiated (objects of modules cannot be created) and do not have an inheritance chain in the same sense as classes.