Govur University Logo
--> --> --> -->
...

Explain the concept of metaprogramming in Ruby and provide an example of its usage.



Metaprogramming in Ruby refers to the ability of a program to modify or generate code at runtime. It allows developers to write code that can create, modify, or inspect code itself. This dynamic aspect of Ruby enables powerful and flexible programming techniques.

One of the key features of metaprogramming in Ruby is the ability to define methods dynamically. Ruby provides methods like `define_method` and `method_missing` that allow developers to create methods on the fly, giving the program the ability to respond to messages that were not predefined.

Here's an example that demonstrates metaprogramming in Ruby:

```
ruby`class MyClass
# Define multiple methods dynamically
['apple', 'banana', 'cherry'].each do |fruit|
define\_method("eat\_#{fruit}") do
puts "Eating #{fruit}"
end
end

# Handle method calls for undefined methods
def method\_missing(method\_name, args)
puts "Oops! You called #{method\_name} method, but it doesn't exist."
end
end

obj = MyClass.new
obj.eat_apple # Output: Eating apple
obj.eat_banana # Output: Eating banana
obj.eat_cherry # Output: Eating cherry
obj.eat_mango # Output: Oops! You called eat\_mango method, but it doesn't exist.`
```
In the above example, the `MyClass` defines methods dynamically based on an array of fruits. Using the `define_method` method, we create methods `eat_apple`, `eat_banana`, and `eat_cherry` dynamically. Each of these methods simply outputs a string indicating that the fruit is being eaten.

Additionally, the `MyClass` also defines a `method_missing` method. This method is invoked when an undefined method is called on an instance of `MyClass`. It allows us to handle and respond to such method calls gracefully. In this case, it outputs an error message indicating that the called method doesn't exist.

Metaprogramming in Ruby provides great flexibility and allows developers to write more expressive and concise code. It can be used to create domain-specific languages (DSLs), define dynamic behavior, add functionalities to existing classes, and more. However, it is important to use metaprogramming judiciously and maintain code readability and maintainability, as excessive use of metaprogramming techniques can make code harder to understand and debug.