Method Introspection in Ruby

July 15, 2011
If, at runtime, you want to find out what the argument names of a Ruby method are, you can use method introspection:

1 2 3 4 5 6 7 8 9 10 11 12
include Test::Unit::Assertions
#=> Object
m = method(:assert_in_delta)
#=> #<Method: Object(MiniTest::Assertions)#assert_in_delta>
m.methods - Object.methods
#=> [:call, :[], :arity, :to_proc, :receiver, :owner, :unbind, :source_location, :parameters]
m.parameters
#=> [[:req, :exp], [:req, :act], [:opt, :delta], [:opt, :msg]]
m.arity
#=> -3
m.source_location
#=> ["/Users/andrew/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/minitest/unit.rb", 122]

Yay for meta programming! And possibly useful for building a dynamic interfaces.

Discussion, links, and tweets

I work at Venture Spirit. Follow me on Twitter; you'll enjoy my tweets. I take care to carefully craft each one. Or at least aim to make you giggle. Or offended. One of those two— I haven't decided which yet.