Railstic

sharing experiences

Dynamically Defining Methods with define_method

| Comments

If you have been hacking ruby for a while you should have heard that “Everything is an object”. To understand this concept knowing what a singleton class is important. Yehuda Katz’s post is a good source for it.

My ruby version 1.9.2.

First I’m going to show you how to add methods to instances by using define_method.

You can also write an instance method to create instance methods. send must be used because define_method is private.

Write a singleton method to create instance methods.

Now it is time to add singleton methods. When we call define_method, it creates an instance method. What we have to do is call define_method on class’ singleton class.

Getting singleton class of a class:

First defining singleton method to create singleton methods.

Then defining instance method to create singleton methods.

Comments