Method: Module#define_method

Defined in:
proc.c

#define_method(symbol, method) ⇒ Object #define_method(symbol) { ... } ⇒ Proc

Defines an instance method in the receiver. The method parameter can be a Proc, a Method or an UnboundMethod object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval, a point that is tricky to demonstrate because define_method is private. (This is why we resort to the send hack in this example.)

class A
  def fred
    puts "In Fred"
  end
  def create_method(name, &block)
    self.class.send(:define_method, name, &block)
  end
  define_method(:wilma) { puts "Charge it!" }
end
class B < A
  define_method(:barney, instance_method(:fred))
end
a = B.new
a.barney
a.wilma
a.create_method(:betty) { p self }
a.betty

produces:

In Fred
Charge it!
#<B:0x401b39e8>

Overloads:

  • #define_method(symbol) { ... } ⇒ Proc

    Yields:

    Returns:



# File 'proc.c'

static VALUE
rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
{
ID id;
VALUE body;
int noex = NOEX_PUBLIC;

if (argc == 1) {
id = rb_to_id(argv[0]);
body = rb_block_lambda();
}