打印Ruby块的源代码

我有一个方法,需要一个块。

显然我不知道将要传递什么,并且出于奇怪的原因我不会进入这里我想要打印块的内容。

有没有办法做到这一点?

您可以使用实现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 } 

将输出:

 "proc { some(code) }" 

我还要看看Github的Chris Wanstrath的这个精彩演讲http://goruco2008.confreaks.com/03_wanstrath.html他展示了一些有趣的ruby2ruby和parsetree用法示例。

基于Evangenieur的回答,如果你有Ruby 1.9,这是Corban的答案:

 # Works with Ruby 1.9 require 'sourcify' def meth &block # Note it's to_source, not to_ruby puts block.to_source end meth { some code } 

我的公司使用它来显示用于进行碳计算的Ruby代码……我们使用ParseTree和Ruby 1.8,现在使用Ruby 1.9进行validation 。

在Ruby 1.9中,您可以尝试从源文件中提取代码的gem。

https://github.com/ngty/sourcify

在Ruby 1.9+(使用2.1.2测试)中,您可以使用https://github.com/banister/method_source

通过block#source #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! 

请注意,为了读取源,您需要使用文件并执行该文件(从irb中测试它将导致以下错误: MethodSource::SourceNotFoundError: Could not load source for : No such file or directory @ rb_sysopen - (irb)