How to Integrate Metaprogramming Techniques Into a Custom Class in Ruby
Now that you have gone through the introduction to metaprogramming guide we have a basic idea about metaprogramming, let's see how to integrate it into a custom class in Ruby.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that you have gone through the introduction to metaprogramming guide 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

If you instantiate it and call a method like this,

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 later lesson we'll walk through how to create methods on the fly, but for right now let's simply open the Baseball class and add the method manually. For example:

class Baseball
end

class Baseball
  def swing
    "Homerun"
  end
end

p Baseball.new.swing

If you run this program, it returns the message Homerun. 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 that in a large Ruby program with hundreds of files, then this type of flexibility is very beneficial.

Returning our Baseball class, we even have the ability to open it again to override the swing method, like this:

class Baseball
end

class Baseball
  def swing
    "Homerun"
  end
end

p Baseball.new.swing # > Homerun

class Baseball
  def swing
    "Strike"
  end
end

p Baseball.new.swing  # > Strike

If you execute this method, the output of the second swing call would be Strike.

Hope this gives you a good idea of metaprogramming in Ruby. This still only is focusing on opening and closing classes. In future guides we'll walk through how method_missing works, which is the core component utilized in Ruby metaprogramming. With that being said, when it comes to day to day development I probably use the process of opening and closing classes more than any other metaprogramming tool.