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,
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.
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.
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