From: dblack@... Date: 2002-12-19T03:52:07+09:00 Subject: Re: Mommy, where do methods come from? Hi -- On Thu, 19 Dec 2002, Chris Pine wrote: > (Sorry for the subject; couldn't help myself! :) > > My (quite serious) question: > > Is there a way to tell in which module an object's method was defined? > > For example: > > class Foo > def to_s; 'foo'; end > end > > class Bar; end > > foo = Foo.new > bar = Bar.new > > foo.methodClass :to_s # Hopefully returns Foo. > bar.methodClass :to_s # Hopefully returns Object. > > > Furthermore, is there a way to tell all of the modules which did define a > method for a given object? > > foo.methodClasses :to_s # Hopefully returns [Foo, Object]. class Object def mc(meth,mess) self.class.ancestors.send(mess) {|mod| mod.instance_methods.include?(meth.to_s) } end def method_class(meth) mc(meth,:detect) end def method_classes(meth) mc(meth,:select) end end p "".method_class("to_s") # String p Object.new.method_class("to_s") # Kernel p "".method_classes("to_s") # [String, Kernel] class Foo def to_s; end end foo = Foo.new p foo.method_classes("to_s") # [Foo, Kernel] David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav