Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Module#method_defined?
(::interned name, ?::boolish inherit) -> bool
mod.method_defined?(symbol, inherit=true, include_all = false) → true or false
mod.method_defined?(string, inherit=true, include_all = false) → true or false
vm_method.c
View on GitHub ↗
static VALUE
rb_mod_method_defined(int argc, VALUE *argv, VALUE mod)
{
VALUE mid, include_super, include_private;
rb_scan_args(argc, argv, "12", &mid, &include_super, &include_private);
if (argc < 3) {
include_private = Qfalse;
if (argc < 2) {
include_super = Qtrue;
}
}
rb_method_visibility_t visi = check_definition_visibility(mod, mid, RTEST(include_super));
switch (visi) {
case METHOD_VISI_UNDEF:
return Qfalse;
case METHOD_VISI_PUBLIC:
case METHOD_VISI_PROTECTED:
return Qtrue;
case METHOD_VISI_PRIVATE:
return RBOOL(RTEST(include_private));
default:
UNREACHABLE_RETURN(Qundef);
}
}
Returns true if the named method is defined by mod. If inherit is set, the lookup will also search mod’s ancestors. By default only public and protected methods are matched, but if include_all is set the lookup will also consider private methods. String arguments are converted to symbols.
Example
module A def method1() end def protected_method1() end protected :protected_method1 end class B def method2() end def private_method2() end private :private_method2 end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.method_defined? "method1" #=> true C.method_defined? "method2" #=> true C.method_defined? "method2", true #=> true C.method_defined? "method2", false #=> false C.method_defined? "method3" #=> true C.method_defined? "protected_method1" #=> true C.method_defined? "method4" #=> false C.method_defined? "private_method2" #=> false C.method_defined? "private_method2", true, true #=> true C.method_defined? "private_method2", false, true #=> false
Ruby version changes
-
4.1
-
Module#method_defined?now accepts a third optional argument to also match private methods. [Feature #22297]
-
See also
#method_added
#method_removed
#instance_methods
#method_undefined
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0