Last Updated: February 25, 2016
·
609
· macfanatic

Find arguments from Ruby method

I think most of us will know that you can define a method with the splat operator and then treat that as an array to your hearts content.

def my_method(*args)
  puts args
end

However, what I didn't know how to do was to easily get the number of arguments from a method when you didn't define it, or when you don't want to use the splat operator.

class Example
  def test(first, second, third='optional')
  end
end
puts Example.method(:test).parameters

That will even show you if the param is required or not. Found on stack overflow of course.

http://stackoverflow.com/a/9212198