How to integrate metaprogramming techniques into a custom class
Now that you have gone through the Metaprogramming introduction section, let's see how to integrate it into a custom class in Ruby.
To start, let's create an empty Baseball
class:
class Baseball end
Now, we instantiate it and call a method using the following code:
p Baseball.new.swing
You'll get an error, and this is good because we don't have a method called swing
in the Baseball
class.
In a later lesson, we'll walk through the process of creating methods on the fly, but right now, let's simply open the Baseball
class and add the method manually:
class Baseball end class Baseball def swing "Homerun" end end p Baseball.new.swing
If you run this program, it will return the "Homerun"
message. This example shows the flexibility that Ruby offers when you want to reopen a class and make changes to it. Since this is a basic example, it doesn't make much of a difference. But if you have to do this in a large Ruby program with...