Method: Module#define_method
- Defined in:
- proc.c
#define_method(symbol, method) ⇒ Object #define_method(symbol) { ... } ⇒ Object
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.
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.
a.wilma
a.flint('Dino')
a.create_method(:betty) { p self }
a.betty
produces:
In Fred
Charge it!
I'm Dino!
#<B:0x401b39e8>
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 |
# File 'proc.c', line 2350
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);
}
|