Get only the non-inherited methods of a class

  • Thread starter toastkid.williams
  • Start date
T

toastkid.williams

Does anyone know how to get the methods of a class in such a way as to
*not* get inherited ones?

For example, the Rails class AbstractRequest has 20 or so methods, all
of which can be called with no parameters. I can call them all,
displaying the name of the method, and the result of calling it with an
empty parameter list, with


request.class.methods.each do |m|
method = request.class.method(m)
puts " #{m} = #{method.call}, "
end

This would produce

accepts = text/htmlapplication/xmlimage/pngtext/plain*/*
delete? = false
etc

However, calling the above also gets all the inherited methods as well,
many of which require parameters, and the code breaks because i'm not
supplying them.

Is there some sort of test that i can do to see if a class creates a
method, rather than inheriting it? I'm thinking of possible solutions,
like recursing up the superclass chain, and not calling the method if
any superclass responds to it, but this seems very complicated for such
a simple problem.

Any ideas, anyone?

thanks
max
 
S

shortcutter

2007/11/2 said:
Hi,

In message "Re: Get only the non-inherited methods of a class"

|Does anyone know how to get the methods of a class in such a way as to
|*not* get inherited ones?

Giving false to #methods.

Stringh.methods
=> ["inspect", "send", "class_eval",...
String.methods(false)
=> []

I guess when invoked on the class instance then it should probably be
String.instance_methods and String.instance_methods(false). If
invoked on the instance then methods and methods(false) should be
appropriate.

Kind regards

robert
 
T

toastkid.williams

Yukihiro said:
Giving false to #methods.

Stringh.methods
=> ["inspect", "send", "class_eval",...
String.methods(false)
=> []

Thanks matz, but why does that return an empty array? Shouldn't it be

["%", "*", "+", "<<", etc]?

(actually for me it returns ["yaml_new", "yaml_tag_subclasses?"], each
of which gives me a NoMethodError when i try to call it on a string)

Would you mind explaining what passing false to methods does?

thanks!
 
T

toastkid.williams

Yukihiro said:
I thought you want class methods of String class. If you want to get
instance_methods of a class C, call

C.instance_methods(false)

Fantastic, thanks! And thanks for Ruby :D
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top