如何动态获取方法的源代码以及该方法位于哪个文件中

我想知道我是否可以即时获取源代码方法,以及是否可以获取该方法位于哪个文件中。


喜欢


A.new.method(:a).SOURCE_CODE

A.new.method(:a).FILE


月关宝盒
浏览 564回答 3
3回答

交互式爱情

用途source_location:class A  def foo  endendfile, line = A.instance_method(:foo).source_location# orfile, line = A.new.method(:foo).source_locationputs "Method foo is defined in #{file}, line #{line}"# => "Method foo is defined in temp.rb, line 2"请注意,对于内置方法,source_location返回nil。如果要查看C源代码(玩得开心!),则必须查找正确的C文件(它们或多或少是按类组织的),并找到rb_define_method方法的方法(在文件末尾) )。在Ruby 1.8中,此方法不存在,但是可以使用gem。

慕慕森

没有依赖method = SomeConstant.method(:some_method_name)file_path, line = method.source_location# puts 10 lines start from the method define&nbsp;IO.readlines(file_path)[line-1, 10]如果您想更方便地使用它,可以打开Method该类:# ~/.irbrcclass Method&nbsp; def source(limit=10)&nbsp; &nbsp; file, line = source_location&nbsp; &nbsp; if file && line&nbsp; &nbsp; &nbsp; IO.readlines(file)[line-1,limit]&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; nil&nbsp; &nbsp; end&nbsp; endend然后打电话 method.source根据Pry在codde-browing中的文档,使用Pry,您可以使用show-method来查看方法源,甚至可以看到pry-doc已安装的一些ruby c源代码。注意,我们也可以使用pry-doc插件查看C方法(从Ruby Core);我们还展示了show-method的替代语法:pry(main)> show-method Array#selectFrom: array.c in Ruby Core (C Method):Number of lines: 15static VALUErb_ary_select(VALUE ary){&nbsp; &nbsp; VALUE result;&nbsp; &nbsp; long i;&nbsp; &nbsp; RETURN_ENUMERATOR(ary, 0, 0);&nbsp; &nbsp; result = rb_ary_new2(RARRAY_LEN(ary));&nbsp; &nbsp; for (i = 0; i < RARRAY_LEN(ary); i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (RTEST(rb_yield(RARRAY_PTR(ary)[i]))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rb_ary_push(result, rb_ary_elt(ary, i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Ruby