给定一个Proc对象,可以查看其中的代码吗?
例如:
p = Proc.new{test = 0}
我需要的是通过某种方式从已经创建的Proc对象中获取字符串"test = 0“。
发布于 2011-01-27 08:10:45
您可以使用ruby2ruby库:
>> # tested with 1.8.7
>> require "parse_tree"
=> true
>> require "ruby2ruby"
=> true
>> require "parse_tree_extensions"
=> true
>> p = Proc.new{test = 0}
>> p.to_ruby
=> "proc { test = 0 }"
您还可以将proc的字符串表示形式转换回ruby,并将其调用:
>> eval(p.to_ruby).call
0
有关ruby2ruby的更多信息,请访问以下视频:Hacking with ruby2ruby。
发布于 2011-01-28 00:10:41
如果你使用的是Ruby1.9,你可以使用the sourcify gem
$ irb
ruby-1.9.2-p0 > require 'sourcify'
=> true
ruby-1.9.2-p0 > p = Proc.new{test = 0}
=> #<Proc:0xa4b166c@(irb):2>
ruby-1.9.2-p0 > p.to_source
=> "proc { test = 0 }"
发布于 2011-01-27 07:54:32
使用proc.source_location
获取定义过程的源文件的位置。它还返回定义的行号。您可以使用这些值来定位proc源的位置。
https://stackoverflow.com/questions/4811501
复制相似问题