Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Module.method_defined?(:method) work correctly?

Tags:

ruby

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??

like image 250
John Duff Avatar asked Dec 31 '09 03:12

John Duff


People also ask

What is the difference between a method and a function?

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.

What is a method in Python?

:-) 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.

What is the difference between method parameters and custom attributes?

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.

Can a method take an instance as its first argument?

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:


2 Answers

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
like image 113
Waheed Avatar answered Sep 18 '22 10:09

Waheed


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.

like image 35
paradigmatic Avatar answered Sep 20 '22 10:09

paradigmatic