I'm trying to check if a method is defined in a module using Module.method_defined?(:method)
and it is returning false it should be returing true.
module Something
def self.another
1
end
end
Something.methods
has 'another' listed but Something.method_defined?(:another)
returns false
.
Is this maybe not working because the method is defined on self? If this is the case is there another way to check if the method is defined on the module other than using method_defined?
?
A function differs from a method in the following ways. While a method is called on an object, a function is generic. Since we call a method on an object, it is associated with it. Consequently, it is able to access and operate on the data within the class.
:-) A method is a function that is stored as a class attribute. You can declare and access such a function this way: What Python tells you here, is that the attribute get_size of the class Pizza is a method that is unbound.
Determines whether any custom attributes are applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter. Determines whether any custom attributes are applied to a module.
And a method wants an instance as its first argument (in Python 2 it must be an instance of that class; in Python 3 it could be anything). Let's try to do that then:
I'm adding my version of the answer
Using the singleton_methods method:
module Something
def self.another
end
end
Something.singleton_methods.include?(:another) #=> true, with all parent modules
Something.singleton_methods(false).include?(:another) #=> true, will check only in the Something module
Modules methods are defined in its metaclass. So you can also check for method inclusion with:
k = class << Something; self; end # Retrieves the metaclass
k.method_defined?(:another) #=> true
You can read more about it in Understanding Ruby Metaclasses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With