0
0
Rubyprogramming~5 mins

Define_method for dynamic methods in Ruby

Choose your learning style9 modes available
Introduction

Define_method lets you create methods on the fly. This helps when you want many similar methods without writing each one by hand.

When you want to create many similar methods that differ only by name or small behavior.
When method names depend on user input or data you get while the program runs.
When you want to keep your code shorter and easier to change later.
When you want to add methods to a class dynamically based on conditions.
When you want to avoid repeating similar code for each method.
Syntax
Ruby
define_method(:method_name) do |parameters|
  # method body
end

The method name is given as a symbol (like :method_name).

The block after define_method is the code that runs when the method is called.

Examples
This creates a method named hello that prints "Hello!".
Ruby
class Greeter
  define_method(:hello) do
    puts "Hello!"
  end
end
This creates a method add that takes two numbers and returns their sum.
Ruby
class Calculator
  define_method(:add) do |a, b|
    a + b
  end
end
This creates three methods: walk, run, and jump, each printing a message.
Ruby
class Person
  [:walk, :run, :jump].each do |action|
    define_method(action) do
      puts "I can #{action}!"
    end
  end
end
Sample Program

This program creates an Animal class. It adds three methods dynamically: speak, eat, and sleep. Each method prints what the animal can do.

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

  [:speak, :eat, :sleep].each do |action|
    define_method(action) do
      puts "#{@name} can #{action}."
    end
  end
end

cat = Animal.new("Cat")
cat.speak
cat.eat
cat.sleep
OutputSuccess
Important Notes

Methods created with define_method can access instance variables like @name.

You can pass parameters to these methods just like normal methods.

Using define_method helps keep your code DRY (Don't Repeat Yourself).

Summary

define_method creates methods during program run, not just when writing code.

It is useful for making many similar methods without repeating code.

Dynamic methods can use parameters and instance variables normally.