Skip to content

Instantly share code, notes, and snippets.

@andruby
Created July 15, 2011 12:18
Show Gist options
  • Save andruby/1084588 to your computer and use it in GitHub Desktop.
Save andruby/1084588 to your computer and use it in GitHub Desktop.
method introspection in Ruby 1.9.2
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]
class Car
def initialize(fuel_type, passenger_capacity, door = 3)
puts "TODO"
end
end
Car.instance_method(:initialize).parameters
#=> [[:req, :fuel_type], [:req, :passenger_capacity], [:opt, :door]]
@andruby
Copy link
Author

andruby commented Jul 15, 2011

Method introspection works on all methods in Ruby. Also methods defined in Kernel (without source_location).

This is a great way to dynamically inspect the names of the arguments passed to any method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment