1

I am looking to get the default values for a function with keyword arguments. Example:

def some_method(foo: 1, bar: 2) end 

My expected output would be something like

{ foo: 1, bar: 2 } 

The parameters method defined on method only provides parameter names.

1

1 Answer 1

1

You can get the keys, but not the values, because they aren't actually set until the method is actually invoked. You can get the method's parameters using Method#parameters. For example, using your example code from above:

method(:some_method).parameters #=> [[:key, :foo], [:key, :bar]] 

However, the :foo and :bar keys aren't actually set until the method is run, so there's no way to get the "value" except possibly to introspect the method definition itself.

Sign up to request clarification or add additional context in comments.

3 Comments

I can use introspection to do it, but I am having difficulty coming up with a good solution.
@MarkRamasco If you're running from a file, you might be able to do it with RBS and/or TypeProf, or simply grepping for the method definition and parsing it. However, from a REPL, you can't access the source in irb, and would probably need to hijack stdout from pry (which is generally a bad idea) to match against output from show-source or show-method. Since I explained that Ruby doesn't set the default arguments until invoked, you might get better answers if you explain your use case; this may be an X/Y problem.
Without going into too much detail, I had to write an adapter around a custom legacy framework for writing tests. This was built on years of work, so it's not a scenario that we can easily change. Essentially, the framework allows someone to write a description that uses string interpolation to fill in values from the test input parameters. This is one of those scenarios where everything is wrong, but I needed to find a work around solution. I ended up with a really janky work around where I use sorcerer to parse the source.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.