get the name of a method's parameter

L

Le Huy

Does anyone know how to use reflection to get the name of a parameter of
a method ?
It is useful for documenting a class and doing editor with code
completion
 
L

Logan Capaldo

def meth(argy)



The problem with this solution is that it does not get the name of the
variable that it was called with, just what it's assigned to (and not
entirely useful, though definitely not useless). I think Le is
asking about
how to get the name of the variable where the value is being copied
to argy
from.

M.T.

I don't think so, the OP said:

It is useful for documenting a class and doing editor with code
completion

which leaves me to believe he's interested in the parameter names for
the method definition. (It would be silly (well maybe just extreme)
to document every callsite).
 
L

Logan Capaldo

You may be right. Well, if so, then your solution works like a
charm. If
not, then there's no solution.

My solution? I had no solutions, just random commentary. ;) (And
there is of course the set_trace_func based solution combined with
reading the source file)
 
S

Sam Smoot

This is an ugly hack, and isn't very pretty in usage, plus it's got
lots of holes I'm sure, but:

module ParameterInspector
def self.included(base)
base.extend ClassMethods
end

module ClassMethods
def find_method_declaration(m)
cat[/def\s+#{m}($|\(.*)/]
end

def find_parameter(method_name, arity)
find_method_declaration(method_name)[/\(.*\)/][1...-1].split(',')[arity]
end

def cat
File.read(self.file)
end
end
end

Then to use it, you must write a class that defines a ::file method,
and include it.

class Example

include ParameterInspector

def self.file
__FILE__
end

def say(something)
puts something
end
end

puts Example.find_parameter :say, 0
"something"
 

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,211
Messages
2,571,100
Members
47,695
Latest member
KayleneBee

Latest Threads

Top