Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Object#singleton_method
(::interned name) -> ::Method
obj.singleton_method(sym) → method
proc.c
View on GitHub ↗
VALUE
rb_obj_singleton_method(VALUE obj, VALUE vid)
{
VALUE sc = rb_singleton_class_get(obj);
VALUE klass;
ID id = rb_check_id(&vid);
if (NIL_P(sc) ||
NIL_P(klass = RCLASS_ORIGIN(sc)) ||
!NIL_P(rb_special_singleton_class(obj))) {
/* goto undef; */
}
else if (! id) {
VALUE m = mnew_missing_by_name(klass, obj, &vid, FALSE, rb_cMethod);
if (m) return m;
/* else goto undef; */
}
else {
VALUE args[2] = {obj, vid};
VALUE ruby_method = rb_rescue(rb_obj_singleton_method_lookup, (VALUE)args, rb_obj_singleton_method_lookup_fail, Qfalse);
if (ruby_method) {
struct METHOD *method = (struct METHOD *)RTYPEDDATA_GET_DATA(ruby_method);
VALUE lookup_class = RBASIC_CLASS(obj);
VALUE stop_class = rb_class_superclass(sc);
VALUE method_class = method->iclass;
/* Determine if method is in singleton class, or module included in or prepended to it */
do {
if (lookup_class == method_class) {
return ruby_method;
}
lookup_class = RCLASS_SUPER(lookup_class);
} while (lookup_class && lookup_class != stop_class);
}
}
/* undef: */
vid = ID2SYM(id);
rb_name_err_raise("undefined singleton method '%1$s' for '%2$s'",
obj, vid);
UNREACHABLE_RETURN(Qundef);
}
Similar to method, searches singleton method only.
Example
class Demo def initialize(n) @iv = n end def hello() "Hello, @iv = #{@iv}" end end k = Demo.new(99) def k.hi "Hi, @iv = #{@iv}" end m = k.singleton_method(:hi) m.call #=> "Hi, @iv = 99" m = k.singleton_method(:hello) #=> NameError
Ruby version changes
-
3.4
-
Object#singleton_methodnow returns methods in modules prepended to or included in the receiver’s singleton class. [Bug #20620]Exampleo = Object.new o.extend(Module.new{def a = 1}) o.singleton_method(:a).call #=> 1
-
See also
#singleton_class
#singleton_methods
#send
#to_enum
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0