给定一个proc对象,是否可以查看其中的代码?
例如:
p = Proc.new{test = 0}
我需要的是某种方式从已经创建的proc对象中获取字符串“test=0”。
Ruby#number0#
$ 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 }"
>> # 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