Implementing metaprogramming with define_method

In this section, you'll learn about another metaprogramming mechanism called define _method that will allow you to dynamically create methods at runtime in a Ruby program.

We'll continue with our Author class and use a method called define_method here:

class Author  define_method("some_method") do    puts "Some details"  endend 

Next, we'll call this method:

author = Author.newauthor.some_method  

When you run this code, it'll print out the Some details value.

You may wonder how this is different from a regular method, such as this one:

def some_method  puts "Some details"end 

The answer is, they are the same!

So, this is not the kind of implementation you'd use define_method for in the real world. ...

Get Comprehensive Ruby Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.