Metaprogramming in Ruby

There comes a time late at night when I can’t sleep where I start some extreme research on a certain topic. Consuming as much useless information on a certain topic as I can. For once my curiosity worked in my favor and I struck gold. I was researching ruby at the time and as I begin to read different blogs and the more I researched the more I came across this mystery of metaprogramming.

If your not familiar Ruby is a fairly new language in software engineering that focuses on object-orientation. Ruby, in my opinion, is awesome because of how dynamic it is as well as how readable it is to non-programmers. The fact that anyone can be able to look at the ruby code and get the gist of what it does is incredible.

So what is metaprogramming and how does it relate to ruby? According to Wikipedia:

Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime. In many cases, this allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.

Basically, metaprogramming is code that writes code.

Metaprogramming is a technique by which you can write code that writes code by itself dynamically at runtime. This means you can define methods and classes during runtime. Crazy, right? One can do in a few minutes what other languages may take hours to do. By cleverly planning your code and applying the techniques mentioned here, you’ll be able to write code that is DRYer, lighter, more intuitive and more scalable.

Why is this useful?

With this pattern, we have made our code much more flexible. We can easily alter the number of attributes in the class. Now, we’re programming for the future. If and when that data with which we want to initialize our class changes, we only have to change our attr_accessors. Our initialize method is flexible and we can leave it alone. That is one major goal of design in object-oriented programming — the writing of code that accommodates future change and doesn’t require a lot of modification, even as it grows.


Can be written as

Easy, simple and way more useful for the programmer!



Fullstack Engineer | Flatrion Grad ’19 !👩‍💻🏳️‍🌈 🇬🇾 | Likes: Traveling, Cooking, Javascript | Dislikes: Systemic Racism, Small Talk

Love podcasts or audiobooks? Learn on the go with our new app.

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
Shivani Brijmohan

Shivani Brijmohan

Fullstack Engineer | Flatrion Grad ’19 !👩‍💻🏳️‍🌈 🇬🇾 | Likes: Traveling, Cooking, Javascript | Dislikes: Systemic Racism, Small Talk