getting the name of arguments a method takes

D

Didier Prophete

I am wondering if there is a way to programatically get the name of the
arguments a function take.

Say, I have this code:
class MyClass
def my_fct(a, b, c)
end
end

Now, I can easily get a handle to the method 'my_fct' using:
mc = MyClass.new
meth = mc.method:)my_fct)

But how do I get to the list of arguments of 'my_fct' ? I couldn't find
anything like:
meth.arg_list
which would return [ :a, :b, :c ], or something like that.

Is this even possible in ruby ?

-Didier
 
T

Timothy Goddard

I don't believe this is possible, but neither can I think why you would
need to. Please explain what you are trying to achieve as there may be
a better way to accomplish it. If you had a method called clean_swamp
you could obtain the number of arguments required with
method:)clean_swamp).arity but not the names. I'm not even sure these
parameter names are actually stored at all after the method has been
defined.

If you need to include usage instructions you could do something like:

$usage = Hash.new('No usage instructions defined.')

class Method
def usage
$usage[self.to_s]
end

def usage=(new_usage)
$usage[self.to_s] = new_usage
end
end

def clean_swamp(swamp, slime_amount)
swamp.slime -= slime_amount
end

method:)clean_swamp).usage = 'clean_swamp(swamp, slime_amount)'
puts method:)clean_swamp).usage
 

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

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,690
Members
48,796
Latest member
Greg L.

Latest Threads

Top