ruby method to list self keyword arguments

Is there a method that can be called on a method to list the keyword arguments?

What I am looking for is something like

self.keyword_arguments

For example in the following example i am looking for an array:

 [:var1, :var2]
def test( var1: true, var2: false)
  self.keyword_arguments
end 

In Ruby, methods are not first-class objects. Referring to a method already executes it. That’s why we often use symbols to refer to methods via their name. To treat methods in an object-oriented way, Ruby provides the Method class as a wrapper. Once you obtained a Method instance for a method, you can introspect it (or have it introspect itself).

It’s a little complicated, but this is how you would approach it:

def test( var1: true, var2: false)
  method(__method__)
    .parameters
    .filter_map { |k, v| v if k == :key || k == :keyreq }
end

test
#=> [:var1, :var2]

Explanation:

  • method looks up a method by its name and returns its Method instance
  • __method__ returns the current method’s name as a symbol, i.e. :test in the above code (hard-coding it via method(:test) would also work)
  • parameters returns an array for the arguments as type / name pairs

For your method, the latter returns [[:key, :var1], [:key, :var2]] with :key denoting an optional keyword argument (one with default value). :keyreq would denote a required keyword argument (one without default value) but you don’t have any in your method.

There’s also :keyrest for arbitrary keyword arguments like **kwargs. I’ve not included :keyrest in the output because the ** argument name is only for “internal” use by the method and not actually used by the caller to pass those extra keyword arguments.

filter_map then returns the values (i.e. the argument names) for the keys we’re interested in.

Leave a Comment