Thursday, September 15, 2011

Dynamically generating methods with the help of define_method in Ruby

Ruby language provides a very interesting feature with the help of which you can dynamically generate methods at run-time. Yes you have read it correctly, you can write codes which will generate methods for you :).


So how can you do it in ruby ? Well, Ruby provides a method called define_method. This method is a private class method


Here is the syntax :
define_method(symbol, method)
define_method(symbol) { block }

where,
  • symbol is the method name; it can be either a symbol, a string, or a variable whose value contains the method name.
  • method is a lambda or Proc object containing the method logic. 
Let me define a very simple method, which will print a hello message for the demonstration purpose. This example will generate an instance method, therefore we will have to create a object for printing the hello message


class D
  define_method(:hello) do |h|
    puts "Hello !!"
  end
end
C.new.hello('Jack')   => Hello Jack !!



Note that, this is a very simple example. Here I wanted to describe the basic idea of define_method provided in Ruby.

No comments:

Post a Comment