Ruby: Debugging a method's source location and code

Updated . Posted . Visible to the public.

Access the Method object

Dead simple: Get the method object and ask for its owner:

"foo".method(:upcase)
# =>  #<Method: String#upcase> 

"foo".method(:upcase).owner
# => String

Look up a method's source location

Ruby 1.9 adds a method Method#source_location that returns file and line number where that method is defined.

class Example; def method() end; end
# => nil

Example.new.method(:method).source_location
# => ["(irb)", 11] 
 
"foo".method(:upcase).source_location
# => nil # String#upcase is a native method that's defined in C

Look up a method's source code

If your Gemfile comes with method_source Show archive.org snapshot (a dependency of Rails 7+), you can can inspect the source code directly using the Method#source method:

puts User.new.method(:name).source

# =>
# def name
#   "#{first_name} #{last_name}".strip
# end

Also see

Dominik Schöler
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2013-03-20 09:28)