From: Logan Capaldo Date: 2005-12-23T08:12:51+09:00 Subject: Re: How do you know what class defines method foo()? On Dec 22, 2005, at 4:57 PM, Sam Kong wrote: > Hi, folks! > > What's the easiest(simplest) code to find a class/module that first > defines a specific method? > I became curious while I was looking for a document of Array#partition > method. > Actually the method is defined in Enumerable module. > But I couldn't guess that it was defined there until I checked Array > class's doc first. > If the inheritance(or mixin) hierarchy is very complex, it will take > long to find a method. > > The one I can think of is using MyClass.ancestors and > MyClass.instance_methods recursively (or repeatedly). > Is there a better way? > (On my second thought, singleton classes should also be considered, > right?) > > The method prototype might be like... > > #returns a class or module which defines the method > def defined_where(obj, method_name) > ... > end > > Thanks. > > Sam > > Array.method_defined?(:partition) #=> true Enumerable.method_defined?(:partition) #=> true Same for instance_methods.include?. If we loop forward through ancestors, we get Array as the answer. If we loop backwards we get Enumerable. The problem is, looping backwards will get us the wrong answer if Array overrides partition. I can't think of a good why to do this unless there is a Class#overrides? method. (e.g. Array.overrides?(:partition) #=> false ).