访问self.method_added中的变量名称

den*_*iss 5 ruby metaprogramming

我相信Ruby,有一种方法可以访问块中所有局部变量的名称.

def some_method(param1, param2)
  p local_variables
end
Run Code Online (Sandbox Code Playgroud)

每当调用'some_method'时,将打印出param1和param2.不是价值!但变量名称.

现在,我想在self.method_added中实现相同的结果.

每当定义方法时,都会调用self.method_added.我希望能够访问self.method_added中定义的方法的局部变量的名称.例如,

def self.method_added(method_name)
   #prints the variables names of the argument for method method_name
end

def do_something param1, param2
   #crazy stuff
end 
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,当do_something被创建时,我想访问变量名'param1'和'param2'

有没有办法做到这一点?

fjl*_*jlj 0

def self.method_added(method_name)
  p self.instance_method(method_name.to_sym).parameters.collect{|g| g[1]}
end
Run Code Online (Sandbox Code Playgroud)