How Metaprogramming in Ruby works

Ruby has built in support for generating code when you need it. Sometimes you may run into situations of writing too much repetitive code in Ruby. If you want to programmatically define your methods for instance you can use two officially recognized ways of accomplishing it.

You can use define_method to create a method which can utilize location variables as defined at the time of method auto declarations. There are several decorators such as attr_reader that relies on this capability of metaprogramming. The nice feature of this metaprogramming is that Ruby will include this auto generated method in RDoc documentation for you.

However, define_method has several shortcoming including a lack of support for defining a method that takes a block.

Another approach to metaprogramming is to utilize module_eval method and convert string into methods. This feature is not unique to Ruby, but all other language highly regard this capability as dangers unlike Ruby, which embraces it.

Here is a list of metaprogramming examples for your reference.

class MyClass
 def my_method
  put “Hello”
 end
end //standard way

class MyClass
 define_method(‘my_method’) do
  put “Hello”
 end
end //using metaprogramming define_method approach

class MyClass
 module_eval %{def my_method
  put “Hello”
 end}
end //using metaprogramming module_eval approach

String.module_eval %{def my_method
                                          put “Hello”
                                        end}

//using metaprogramming module_eval approach

Ruby develooer , in addition to creating methods via metaprogramming, can remove methods from classes. In order to accomplish this, Ruby provides remove_method method.

class MyClass
  remove_method(:my_method)
end

Removal of a method is allowed only for methods defined within a scope of a class. Methods cannot be removed if they are inherited from superclass or a module. In order to stop a method from responding, you’ll need to use

class MyClass
  undef_method(:my_method)
end

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…