0

Is there a way in Ruby to get the current method's list of arguments and their current value (during method run)? As in:

def foo(a, b, c)
    arg_vals = __method__params__
    return arg_vals
end

 x = foo(10,20,30) #returns {a:10, b:20, c:30}

(Background: I want this for my logging library, so that from any point I could call: )

my_logger(__method__, __method__params__)
sellarafaeli
  • 1,167
  • 2
  • 9
  • 24

1 Answers1

1

It's a bit hacky, but this is close:

def test(arg1, arg2)
    args = local_variables.inject({}) { |c, i| c[i] = eval(i); c }
    puts args.inspect
end

test('hello', 'world')

output:

{"args"=>nil, "arg1"=>"hello", "arg2"=>"world"}

Interactive version: http://repl.it/QTi

Also note that if called near the end of a method, it can give you insight into all of the local variables inside the method, which can be either a benefit or annoying depending on what you are looking for.

Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
  • No it is not correct way to meet OP's need. Only answer pf this post - http://stackoverflow.com/questions/9211813/is-there-a-way-to-access-method-arguments-in-ruby – Arup Rakshit Mar 23 '14 at 10:09