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