Metaprogramming in Ruby

Total Blog Views: 51

Blog Status: publish

Created By: swaz_ahmed Created at: 06-14-2024

Tags: ruby ror programming

Metaprogramming the term may seems difficult, but it is much intresting as it sounds. Lets see the definition of it:

"Metaprogramming is a programming technique where computer programs have the ability to treat other programs as their data. This means that a program can be designed to read, generate, analyze, or transform other programs, and even modify itself while running"

Lets make it more simpler in context of ruby,

Metaprogramming refers to the practice of writing code that generates or manipulates other code. 

In other words, it's the act of creating programs that can modify themselves or create new programs dynamically at runtime. Metaprogramming is a powerful technique in the Ruby programming language due to its dynamic and flexible nature. Ruby allows you to manipulate classes, methods, and even the language itself at runtime, enabling a wide range of metaprogramming possibilities. It is used to make code more flexible, reusable, and adaptable. 

Types of metaprogramming

There are two main types of metaprogramming

1. Compile-time Metaprogramming: This involves manipulating code during the compilation phase of a program.

2. Runtime Metaprogramming: This involves modifying or generating code during the execution of a program. Developers can create new functions, classes, or modify existing code structures during program execution.

In ruby we use runtime metaprogramming as we know ruby directly goes to run phase so below are some metaprogramming techniques we can use in ruby:

  1. define_method
  2. method_missing
  3. send method
  4. open classes

1. define_method

In thie below example, we dynamically define instance methods method_one and method_two for the class MyClass using the define_method method. This allows us to add methods to a class at runtime based on an array of method names.

 

class MyClass
  def self.create_method(method_name)
    define_method(method_name) do
      puts "Hello from #{method_name}!"
    end
  end
end

obj = MyClass.new

# Creating and calling a dynamic method
MyClass.create_method(:dynamic_method)
obj.dynamic_method  # Output: Hello from dynamic_method!

 

2. method_missing
The method_missing method is called when an object receives a method call that it doesn't understand. In this example, we're intercepting method calls starting with "dynamic_" and providing a custom response.

 

class DynamicMethod
  def method_missing(method_name, *args, &block)
    if method_name.to_s.start_with?("dynamic_")
      puts "You called #{method_name} with arguments #{args.join(', ')}"
    else
      super
    end
  end
end

obj = DynamicMethod.new

obj.dynamic_hello("arg1", "arg2")  # Output: You called dynamic_hello with arguments arg1, arg2
obj.some_other_method  # NoMethodError

 

3. send method

The send method in Ruby is an instance method of the object class, which means it is available to all objects in Ruby. It enables us to call a method on an object dynamically, using a string or a symbol representing the name of the method. IN below example we are using define_method to dynamically call methods in OPERATOR and send_method will get called.

 

class DynamicCalculator
  OPERATORS = %w(add subtract multiply divide)

  OPERATORS.each do |operator|
    define_method("calculate_#{operator}") do |a, b|
      send(operator, a, b)
    end
  end
 private

 def add(a, b)
    a + b
 end

  def subtract(a, b)
     a - b
  end
end

calculator = DynamicCalculator.new

puts calculator.calculate_add(5, 3)       # Output: 8
puts calculator.calculate_subtract(10, 4)  # Output: 6

 

4. open classes
Ruby allows you to reopen and modify existing classes. In this example, I have added a shout method to the String class, which converts a string to uppercase and adds exclamation marks.

class String
  def shout
    self.upcase + "!!!"
  end
end
puts "hello".shout  # Output: HELLO!!!


This the basic techniques we can use to imlememt metaprogramming in ruby. Explore more and you will find it more intrestng. Happy coding!


swaz_ahmed

I am swaz_ahmed blogger on shadbox. I am influencer,content writer,author and publisher. Feel free to ask me any question and suggestions.



Comments



Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads