This is useful if you are trying to create class methods metaprogramatically:
def self.create_methods(method_name) # To create instance methods: define_method method_name do ... end # To create class methods that refer to the args on create_methods: ??? end
My answer to follow...
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.
define_method is a method defined in Module class which you can use to create methods dynamically. To use define_method , you call it with the name of the new method and a block where the parameters of the block become the parameters of the new method.
Metaprogramming is a technique in which code operates on code rather than on data. It can be used to write programs that write code dynamically at run time. MetaProgramming gives Ruby the ability to open and modify classes, create methods on the fly and much more.
Ruby is too dynamic. We can do almost anything in runtime, from creating the classes at runtime to creating methods dynamically. If you are coming from some other language, it would be shocking for you too know that nothing is private in ruby.
I think in Ruby 1.9 you can do this:
class A define_singleton_method :loudly do |message| puts message.upcase end end A.loudly "my message" # >> MY MESSAGE
I prefer using send to call define_method, and I also like to create a metaclass method to access the metaclass:
class Object def metaclass class << self self end end end class MyClass # Defines MyClass.my_method self.metaclass.send(:define_method, :my_method) do ... end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With