Getting the name of arguments a method takes

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

Didier Prophete wrote:

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

i also would like to do this. anybody know if it’s possible, and also
getting arg names from a proc? if so it would be very handy for
metaprogramming.

thanks

Guest wrote:

Now, I can easily get a handle to the method ‘my_fct’ using:
-Didier

i also would like to do this. anybody know if it’s possible, and also
getting arg names from a proc? if so it would be very handy for
metaprogramming.

The short answer: no, it’s not possible. What do you want it for?

There’s always this way, though:

def method_arg_names(method_name, file)
File.read(file)[/def #{Regexp.escape method_name}(.*()|$))/, 1]
end

p method_arg_names(“method_arg_names”, $0) #=> “(method_name, file)”

Cheers,
Dave

On Tue, 2006-05-02 at 09:17 +0900, Dave B. wrote:

getting arg names from a proc? if so it would be very handy for
p method_arg_names(“method_arg_names”, $0) #=> “(method_name, file)”

Cheers,
Dave

Also, this, if you’re only dealing with Ruby methods and are in a
kamikaze kind of mood:

class Method
def arg_names
catch(:traced) do
dummy_args = [nil]
dummy_args *= self.arity unless self.arity < 0

  set_trace_func lambda { |event, file, line, id, bdng, cls|
    if event == 'call'
      set_trace_func nil
      throw(:traced, eval('local_variables',bdng).map { |lv| 

lv.intern })
end
}

  self.call(*dummy_args)

  # if we get here, call is bust
  set_trace_func nil
  raise "No ruby method call in block"
end

end
end

Doesn’t work for procs, though.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs