Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use define_method to create class methods?

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

like image 895
Chinasaur Avatar asked Apr 15 '09 17:04

Chinasaur


People also ask

How do you define a class method in Ruby?

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.

What is Define_method?

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.

What is meta programming what methods of meta programming does Ruby support and when why would you use it in a project?

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.

What is dynamic in Ruby?

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.


2 Answers

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 
like image 124
fguillen Avatar answered Sep 28 '22 06:09

fguillen


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 
like image 28
Vincent Robert Avatar answered Sep 28 '22 06:09

Vincent Robert