instance method
Object#define_singleton_method
(::interned name, ::Method | ::UnboundMethod | ::Proc method) -> ::Symbol
(::interned name) { (?) [self: self] -> untyped } -> ::Symbol
define_singleton_method(symbol, method) → symbol
define_singleton_method(symbol) { block } → symbol
proc.c
View on GitHub ↗
static VALUE
rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
{
VALUE klass = rb_singleton_class(obj);
const rb_scope_visibility_t scope_visi = {METHOD_VISI_PUBLIC, FALSE};
return rb_mod_define_method_with_visibility(argc, argv, klass, &scope_visi);
}
Defines a public singleton 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 a method has parameters, they’re used as method parameters.
Example
class A class << self def class_name to_s end end end A.define_singleton_method(:who_am_i) do "I am: #{class_name}" end A.who_am_i # ==> "I am: A" guy = "Bob" guy.define_singleton_method(:hello) { "#{self}: Hello there!" } guy.hello #=> "Bob: Hello there!" chris = "Chris" chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" } chris.greet("Hi") #=> "Hi, I'm Chris!"