打印Ruby块的源代码

Der*_*ins 11 ruby

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

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

有没有办法做到这一点?

Cor*_*ook 9

您可以使用实现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用法示例.


Nic*_*ick 5

在 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)