0
0
Rubyprogramming~7 mins

Module_eval for dynamic behavior in Ruby

Choose your learning style9 modes available
Introduction

Module_eval lets you add or change methods in a module while the program is running. This helps make your code flexible and adapt to new needs without rewriting it.

When you want to add new methods to a module based on user input or configuration.
When you need to change behavior of a module without restarting the program.
When you want to generate methods dynamically to avoid repetitive code.
When experimenting or testing different method definitions quickly.
When building libraries or frameworks that need to customize modules on the fly.
Syntax
Ruby
module ModuleName
  module_eval do
    # method definitions or code here
  end
end

You can pass a string or a block to module_eval.

Code inside module_eval runs as if it is inside the module.

Examples
This adds a method hello to the Greeter module using a block.
Ruby
module Greeter
  module_eval do
    def hello
      "Hello!"
    end
  end
end
This adds a method bye to Greeter using a string.
Ruby
module Greeter
  module_eval "def bye; 'Goodbye!'; end"
end
Defines a method square inside MathOps dynamically.
Ruby
module MathOps
  module_eval do
    def square(x)
      x * x
    end
  end
end
Sample Program

This program creates a module DynamicModule and adds a method greet dynamically using module_eval. Then a class Person includes this module. When we create a Person object and call greet, it prints a greeting.

Ruby
module DynamicModule
  module_eval do
    def greet(name)
      "Hello, #{name}!"
    end
  end
end

class Person
  include DynamicModule
end

p = Person.new
puts p.greet("Alice")
OutputSuccess
Important Notes

Using module_eval can be powerful but also risky if you run untrusted code.

It changes the module at runtime, so debugging can be harder if overused.

Prefer clear and simple code unless you really need dynamic behavior.

Summary

Module_eval lets you add or change methods inside a module while the program runs.

You can pass a block or a string to module_eval to define methods dynamically.

This helps make your code flexible but use it carefully to keep code readable and safe.