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.
Module_eval for dynamic behavior in 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.
hello to the Greeter module using a block.module Greeter module_eval do def hello "Hello!" end end end
bye to Greeter using a string.module Greeter module_eval "def bye; 'Goodbye!'; end" end
square inside MathOps dynamically.module MathOps module_eval do def square(x) x * x end end end
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.
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")
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.
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.