instance method
Module#define_method
(::interned symbol, ^(?) [self: top] -> untyped | ::Method | ::UnboundMethod method) -> ::Symbol
(::interned symbol) { (?) [self: top] -> untyped } -> ::Symbol
define_method(symbol, method) → symbol
define_method(symbol) { block } → symbol
proc.c
View on GitHub ↗
static VALUE
rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
{
const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
const rb_scope_visibility_t *scope_visi = &default_scope_visi;
if (cref) {
scope_visi = CREF_SCOPE_VISI(cref);
}
return rb_mod_define_method_with_visibility(argc, argv, mod, scope_visi);
}
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. If a block or the method parameter has parameters, they’re used as method parameters. This block is evaluated using instance_eval.
Example
class A def fred puts "In Fred" end def create_method(name, &block) self.class.define_method(name, &block) end define_method(:wilma) { puts "Charge it!" } define_method(:flint) {|name| puts "I'm #{name}!"} end class B < A define_method(:barney, instance_method(:fred)) end a = B.new a.barney a.wilma a.flint('Dino') a.create_method(:betty) { p self } a.betty
produces:
In Fred Charge it! I'm Dino! #<B:0x401b39e8>
See also
#const_source_location
#deprecate_constant
#const_set
#extended
also in
4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0