Home > Software engineering >  How to get a list of methods defined in a Ruby class?
How to get a list of methods defined in a Ruby class?

Time:11-17

I am looking for a way to generate a list of all methods within a Ruby Class, similar to a C Header File. I want this so that I can see an overview of the class without using IDE code folding to collapse everything.

Preferably this would be a *nix command line function so that I can further process this using other command line tools.

Output would be something like

def foo( a, b, c )
def bar
def baz( d )

CodePudding user response:

Use instance_methods for that class and then query the parameters

e.g.

class A 
  def foo
  end
  def bar(a,b,c)
  end
end


A.instance_methods(false).each do |s|
   print "def #{s}(#{A.instance_method(s).parameters})\n"
end

Output:

def foo([])
def bar([[:req, :a], [:req, :b], [:req, :c]])

You might need to get subprocess the parameters array to get the name only.

As for command line, just save it into a ruby script.

  • Related