DEV Community

professorjrod
professorjrod

Posted on

An Intro to Metaprogramming in Ruby

Ruby 3.1 comes with some handy built in methods you can use to manipulate existing modules and classes
Define_Method

Image description

> leader = Leader.new
> puts leader.give_money("knight")
=> giving money to knight
> puts leader.give_medal("senior")
=> giving medal to senior
> puts leader.give_title("tax payer")
=> giving title to tax payer
Enter fullscreen mode Exit fullscreen mode

Consider a situation where you have to create a series of methods all of which have the same basic structure save for one string, and which can only be one of a certain set of strings. This approach is declarative - you know what values your parameters can accept.
The usefulness of define_method is when you can call it like any other code. Here's the same example but here it's called inside of a loop.

Image description

> leader = Leader.new
> puts leader.give_money("knight")
=> giving money to knight
> puts leader.give_medal("senior")
=> giving medal to senior
> puts leader.give_title("tax payer")
=> giving title to tax payer
Enter fullscreen mode Exit fullscreen mode

Now we have code generating methods for us. We can extend this by adding elements to the array or by using different data. This is how a lot of Ruby libraries dynamically define methods, such as in database schemas.

Thanks for the read! If there are any other interesting programming paradigms you'd like to read about then drop it in the comments! If you'd like to learn more about how metaprogramming is implemented in Ruby on Rails, check out this great blog post

Top comments (0)