我相信 Ruby,有一种方法可以访问 block 中所有局部变量的名称。
def some_method(param1, param2)
p local_variables
end
每当调用“some_method”时,param1 和 param2 将被打印出来。不是值(value)!但是变量名。
现在,我想在 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
使用上面的代码,当创建 do_something 时,我想访问变量名称“param1”和“param2”
有办法吗?
最佳答案
def self.method_added(method_name)
p self.instance_method(method_name.to_sym).parameters.collect{|g| g[1]}
end
关于ruby - 访问 self.method_added 中的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7239623/