Metaprogramming in Ruby | How metaprogramming works in Ruby? | Techniques in Metaprogrammming?

 


Metaprogramming is a powerful technique that allows me to write or modify the existing code during runtime. Ruby provides powerful features for metaprogramming, making it possible to dynamically define classes, methods, and perform other tasks.

Here are some common techniques that are used in metaprogramming in Ruby:

Dynamic method definition: 

Ruby allows methods to be defined dynamically, using define_method. While describing the class, we defined its structure and behavior. This includes defining instance methods. By using the `define_method` we instruct Ruby to create a method with the given name and implementation dynamically at runtime.

    class Student
        define_method :info do
            puts "My name is Yash" #dynamically defined method
        end
    end
    student = Student.new
    student.info

In the above `Student` class, the `info` method is defined but its implementation is dynamic at runtime.

Eval and Instance Eval:

`eval` takes the string as an argument representing the ruby code to execute at runtime. This means the code to be executed can be dynamically, based on variables.

    puts "Enter the integer value"
    x = gets.chomp.to_i
    eval('puts x*2')

`instance_eval` allows us to execute the code within the context of the specific object.

    class Student
        def initialize(name)
            @name = name
        end
    end

    student = Student.new("Yash")
    student.instance_eval do
        puts @name
    end

Method Missing:

The method_missing is called when the method is invoked which doesn't exist. The method_missing method is invoked dynamically when any method is called that does not exist in the class.

    class Student
        def method_missing(method_name)
            puts "You have to tried to call a #{method_name} method             which is not present in the class"
        end
    end

    student = Student.new
    student.info


While metaprogramming can be powerful, it also comes with risks, as it can make code harder to understand and debug. It's important to use metaprogramming judiciously and consider readability and maintainability when employing these techniques in your code.

Comments