tags:

views:

81

answers:

2

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

+2  A: 

To know whether the module has a module method, you can use respond_to? on the module:

Something.respond_to?(another)
=> true

method_defined? will tell you whether INSTANCES of the class with the module included responds to the given method.

ennuikiller
A: 

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.

paradigmatic
The diagram on that site is confusing to say the least. What does it mean by the instance 'inheriting' the methods from the class? seems like wrong terminology to me. Also what does it mean by the arrow labeled `instance_eval` pointing to the metaclass? `instance_eval` evaluation does not happen on the metaclass, it happens on the instance - the only exception being the behaviour of `def` in an `instance_eval` which instead defines methods on the metaclass.
banister