您可以使用实现to_ruby方法的Ruby2Ruby来完成此操作.
require 'rubygems'
require 'parse_tree'
require 'parse_tree_extensions'
require 'ruby2ruby'
def meth &block
puts block.to_ruby
end
meth { some code }
Run Code Online (Sandbox Code Playgroud)
将输出:
"proc { some(code) }"
Run Code Online (Sandbox Code Playgroud)
我还要看看Github的Chris Wanstrath的这个精彩的演讲http://goruco2008.confreaks.com/03_wanstrath.html他展示了一些有趣的ruby2ruby和parsetree用法示例.
在 Ruby 1.9+(使用 2.1.2 测试)中,您可以使用https://github.com/banister/method_source
通过以下方式打印源代码block#source:
#! /usr/bin/ruby
require 'rubygems'
require 'method_source'
def wait &block
puts "Running the following code: #{block.source}"
puts "Result: #{yield}"
puts "Done"
end
def run!
x = 6
wait { x == 5 }
wait { x == 6 }
end
run!
Run Code Online (Sandbox Code Playgroud)
请注意,为了读取源代码,您需要使用一个文件并执行该文件(从 irb 测试它会导致以下错误:MethodSource::SourceNotFoundError: Could not load source for : No such file or directory @ rb_sysopen - (irb)