Ruby - 获取方法参数名称和值

Ser*_*lto 3 ruby parameters

有没有办法动态获取方法参数名称和值,也许是元编程?

def my_method(name, age)
  # some code that solves this issue
end

my_method('John', 22) # => { name: 'John', age: 22 }
Run Code Online (Sandbox Code Playgroud)

我想在我的所有方法中使用它来记录方法调用和相应的参数,但不需要在每个方法中手动执行此操作。

谢谢。

ymb*_*rtt 5

是的!在 ruby​​ 中,它被称为binding,它是一个封装特定行运行的上下文的对象。完整的文档在这里,但在你想要做什么的情况下......

def my_method(arg1, arg2)
  var = arg2
  p binding.local_variables #=> [:arg1, :arg2, :var]
  p binding.local_variable_get(:arg1) #=> 1
  p Hash[binding.local_variables.map{|x| [x, binding.local_variable_get(x)]}] #=> {:arg1 => 1, :arg2 => 2, :var => 2}
end

my_method(1, 2)
Run Code Online (Sandbox Code Playgroud)

Binding#eval如果您可以提供帮助,我强烈建议您不要这样做。解决问题的方法几乎总是比使用eval. 请注意,binding在调用它的行上封装了上下文,因此如果您希望有一个简单的log_parameters_at_this_point方法,则需要将绑定传递到该方法中,或者使用更聪明的方法,例如binding_of_caller