Mommy, where do methods come from?

Probably you need to traverse through the ancestor tree and use a “-”
operation on the arrays returned by #instance_method to decide which
ancestor defined the method?

I remember I have asked the question before…

Shannon

···

From: dblack@candle.superlink.net
Reply-To: ruby-talk@ruby-lang.org
To: ruby-talk@ruby-lang.org (ruby-talk ML)
Subject: Re: Mommy, where do methods come from?
Date: Thu, 19 Dec 2002 03:52:07 +0900

Hi –

On Thu, 19 Dec 2002, Chris Pine wrote:

(Sorry for the subject; couldn’t help myself! :slight_smile:

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


Add photos to your e-mail with MSN 8. Get 2 months FREE*.
http://join.msn.com/?page=features/featuredemail

Hi –

···

On Thu, 19 Dec 2002, Shannon Fang wrote:

Probably you need to traverse through the ancestor tree and use a “-”
operation on the arrays returned by #instance_method to decide which
ancestor defined the method?

I think my code worked, didn’t it? Did I misunderstand the question?

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav