0
0
Rubyprogramming~5 mins

Why metaprogramming is powerful in Ruby

Choose your learning style9 modes available
Introduction

Metaprogramming lets Ruby programs write or change code while running. This makes programs flexible and saves time.

When you want to create methods automatically instead of writing many similar ones.
When you need to change how a program works without rewriting lots of code.
When building tools that adapt to different situations or data.
When you want to add features to existing code without changing it directly.
Syntax
Ruby
# Example of defining a method dynamically
class MyClass
  define_method(:greet) do |name|
    "Hello, #{name}!"
  end
end
Ruby lets you create or change methods while the program runs.
This helps avoid repeating similar code and makes programs smarter.
Examples
This example creates a method say_hello dynamically that prints a greeting.
Ruby
class Person
  define_method(:say_hello) do
    "Hi!"
  end
end

p = Person.new
puts p.say_hello
This example creates two methods add and subtract dynamically using a loop.
Ruby
class Calculator
  [:add, :subtract].each do |method_name|
    define_method(method_name) do |a, b|
      method_name == :add ? a + b : a - b
    end
  end
end

calc = Calculator.new
puts calc.add(5, 3)
puts calc.subtract(5, 3)
Sample Program

This program creates a Robot class that gets methods walk, talk, and jump automatically. Each method prints what the robot can do.

Ruby
class Robot
  def initialize(name)
    @name = name
  end

  ['walk', 'talk', 'jump'].each do |action|
    define_method(action) do
      "#{@name} can #{action}!"
    end
  end
end

r = Robot.new('Robo')
puts r.walk
puts r.talk
puts r.jump
OutputSuccess
Important Notes

Metaprogramming can make code harder to read if overused, so use it carefully.

It helps reduce repeated code and makes programs more flexible.

Summary

Metaprogramming lets Ruby programs create or change code while running.

This makes programs flexible, saves time, and reduces repeated code.

Use it to add or change methods automatically based on your needs.