End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Module#define_method
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)
{
ID id;
VALUE body;
VALUE name;
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;
int is_method = FALSE;
if (cref) {
scope_visi = CREF_SCOPE_VISI(cref);
}
rb_check_arity(argc, 1, 2);
name = argv[0];
id = rb_check_id(&name);
if (argc == 1) {
body = rb_block_lambda();
}
else {
body = argv[1];
if (rb_obj_is_method(body)) {
is_method = TRUE;
}
else if (rb_obj_is_proc(body)) {
is_method = FALSE;
}
else {
rb_raise(rb_eTypeError,
"wrong argument type %s (expected Proc/Method/UnboundMethod)",
rb_obj_classname(body));
}
}
if (!id) id = rb_to_id(name);
if (is_method) {
struct METHOD *method = (struct METHOD *)DATA_PTR(body);
if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) &&
!RTEST(rb_class_inherited_p(mod, method->me->owner))) {
if (FL_TEST(method->me->owner, FL_SINGLETON)) {
rb_raise(rb_eTypeError,
"can't bind singleton method to a different class");
}
else {
rb_raise(rb_eTypeError,
"bind argument must be a subclass of % "PRIsVALUE,
method->me->owner);
}
}
rb_method_entry_set(mod, id, method->me, scope_visi->method_visi);
if (scope_visi->module_func) {
rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC);
}
RB_GC_GUARD(body);
}
else {
VALUE procval = rb_proc_dup(body);
if (vm_proc_iseq(procval) != NULL) {
rb_proc_t *proc;
GetProcPtr(procval, proc);
proc->is_lambda = TRUE;
proc->is_from_method = TRUE;
}
rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi);
if (scope_visi->module_func) {
rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC);
}
}
return ID2SYM(id);
}
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 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1