An Intro to Metaprogramming in Ruby

Sandra To
Sandra To
Apr 5 · 4 min read
Example for metaprogramming in ruby with define_method

Automagical Properties in Ruby

A word I often see mentioned in Ruby documentations and question boards is the word “automagical”. On the surface, it really does seem like Ruby has automagical variables and methods. However, there is a lot that Ruby does behind the scene, and metaprogramming is the key behind this automagical association.

Defining Metaprogramming

There are various definitions floating around the Internet that try to explain what metaprogramming is. Here are a few:

“Metaprogramming allows programs to create methods on the fly instead of having to define them in the program itself.”

So… what does it really mean?

To really explain what metaprogramming is, we’ll look at three examples:

  1. define_method
  2. method.missing

Monkey Patching

A very powerful and potentially dangerous aspect of Ruby is the ability to open any class and alter its variables and methods. Let’s observe some metaprogramming at work.

Danger of Monkey Patching

define_method

Having now gained a better understanding of how metaprogramming works, we can dive into a slightly more advanced class method in Ruby called define_method. The primary use of define_method is to create methods at application runtime.

method_missing

Our last example will show us one of the most powerful methods of Ruby. The method_missing method allows us to call on methods that do not exist, and define them on the fly.

Summary

Let’s revisit the definitions from the beginning of this article:

More Metaprogramming

CodeX

Everything connected with Tech & Code

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store