Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - get method params names and values [duplicate]

Is there a way to get method parameters names and values dynamically, maybe a metaprogramming?

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

my_method('John', 22) # => { name: 'John', age: 22 }

I want to use this in all my methods in order to log methods calls and respective parameters, but without to do this manually in every method.

Thanks.

like image 227
Seralto Avatar asked Sep 18 '25 19:09

Seralto


1 Answers

Yup! In ruby, it's called the binding, which is an object that encapsulates the context in which a particular line runs. The full docs are here, but in the case of what you're trying to do...

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)

I'd strongly advise against Binding#eval, if you can possibly help it. There's almost always a better way to sovle problems than by using eval. Be aware that binding encapsulates context on the line at which it is called, so if you were hoping to have a simple log_parameters_at_this_point method, you'll either need to pass the binding into that method, or use something cleverer like binding_of_caller

like image 59
ymbirtt Avatar answered Sep 21 '25 11:09

ymbirtt