How can I get source code of a method dynamically and also which file is this method locate in

Use source_location:

class A
  def foo
  end
end

file, line = A.instance_method(:foo).source_location
# or
file, line = A.new.method(:foo).source_location
puts "Method foo is defined in #{file}, line #{line}"
# => "Method foo is defined in temp.rb, line 2"

Note that for builtin methods, source_location returns nil. If want to check out the C source code (have fun!), you'll have to look for the right C file (they're more or less organized by class) and find the rb_define_method for the method (towards the end of the file).

In Ruby 1.8 this method does not exist, but you can use this gem.


None of the answers so far show how to display the source code of a method on the fly...

It's actually very easy if you use the awesome 'method_source' gem by John Mair (the maker of Pry): The method has to be implemented in Ruby (not C), and has to be loaded from a file (not irb).

Here's an example displaying the method source code in the Rails console with method_source:

  $ rails console
  > require 'method_source'
  > I18n::Backend::Simple.instance_method(:lookup).source.display
    def lookup(locale, key, scope = [], options = {})
      init_translations unless initialized?
      keys = I18n.normalize_keys(locale, key, scope, options[:separator])

      keys.inject(translations) do |result, _key|
        _key = _key.to_sym
        return nil unless result.is_a?(Hash) && result.has_key?(_key)
        result = result[_key]
        result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
        result
      end
    end
    => nil 

See also:

  • https://rubygems.org/gems/method_source
  • https://github.com/banister/method_source
  • http://banisterfiend.wordpress.com/

Here is how to print out the source code from ruby:

puts File.read(OBJECT_TO_GET.method(:METHOD_FROM).source_location[0])

Tags:

Ruby