Ruby - define_method Example

1. Introduction

In this post, we will explore how to use define_method to define methods dynamically at runtime.

Definition

define_method is a private instance method of the Module class. It allows developers to define methods dynamically, by providing a method name and a block that serves as the body of the method. This enables the creation of methods on the fly based on program logic or data.

2. Program Steps

1. Define a class to showcase dynamic method creation.

2. Use define_method within the class context to create methods dynamically.

3. Invoke the dynamically created methods.

3. Code Program

class DynamicMethodCreator
  # Define methods dynamically
  ["ruby", "python", "javascript"].each do |lang|
    define_method("print_#{lang}") do
      puts "I love #{lang.capitalize}!"
    end
  end
end
# Instantiate the class and call the dynamically defined methods
dynamic = DynamicMethodCreator.new
dynamic.print_ruby
dynamic.print_python
dynamic.print_javascript

Output:

I love Ruby!
I love Python!
I love Javascript!

Explanation:

1. We define a class DynamicMethodCreator that will illustrate the use of define_method.

2. Inside the class context, we iterate over an array of programming language names. For each name, we use define_method to create a new method. The method's name is dynamically generated based on the language name (like print_ruby, print_python, etc.).

3. The block provided to define_method defines the behavior of the dynamically created method. In this example, each method prints out a statement expressing love for the respective programming language.

4. We then create an instance of the DynamicMethodCreator class and invoke the dynamically defined methods. They behave as if they were explicitly written in the class.

5. This approach showcases the power and flexibility of Ruby, enabling programmers to adapt the code based on data or other runtime conditions.

Using define_method can significantly enhance the flexibility of Ruby programs, but as with all metaprogramming tools, it should be used judiciously to ensure code maintainability and readability.


Comments