Find where a method is defined in Ruby

By | June 2, 2011

There are times when you might be working on a codebase with other people and spot a method which you do not know about. You may want to locate the source of that method to learn and understand more about its functionality.

So, Here is a quick tip on how to find where a method is defined or located.

I was working on a project where i found this piece of code -

var = Class.method :foo.eql => foo, :bar.eql => bar[:baz]

I did not know about the eql method, so in order to locate its source file I simply added a piece of code -

puts :foo.method(:eql).source_location.to_s

To break that down, method is a method of Object class that returns a Method class's object. So :foo.method(:eql) returns a Method object and then calling source_location on it gives an array where the first element is usually the source file's location and the second element is the line number.

To know more, check out these 2 links -

:foo.method(:eql).source_location basically returned an array # => ["/usr/local/lib/ruby/gems/1.9.1/gems/dm-core-1.0.2/lib/dm-core/core_ext/symbol.rb", 4]

Hope that helps. Cheers!

Last Updated On : 2nd June 2011

Leave a Reply

Your email address will not be published. Required fields are marked *