Saturday, October 27, 2012

Ruby get method arguments

So, say you are writing some Ruby code, and want to get an overview of the arguments for a method, dynamically.

Consider this method with arguments a and b:

def foobar a, b
end

Using method(...), we can pass in the special variable __method__ to get the current method.

In turn, we can get the parameters of the method with .parameters, and we can then iterate over the parameters.

Now our code would look something like this:

def foobar a, b
  method(__method__).parameters.each do |arg|
    # ...
  end
end

In order to get the correct parameter name with it's associated value, the final solution would be:

def foobar a, b
  method(__method__).parameters.each do |arg|
    val = eval arg[1].to_s
    puts "#{arg[1]}: #{val}, #{val.class}"
  end
end

Happy coding!

No comments:

Post a Comment