I would like to know whether I can get source code a method on the fly, and whether I can get which file is this method in.
like
A.new.method(:a).SOURCE_CODE A.new.method(:a).FILE
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With