代码之家  ›  专栏  ›  技术社区  ›  Derek Ekins

打印Ruby块的源代码

  •  11
  • Derek Ekins  · 技术社区  · 15 年前

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

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

    有办法吗?

    4 回复  |  直到 9 年前
        1
  •  9
  •   Corban Brook    15 年前

    您可以使用Ruby2Ruby实现一个to-Ruby方法。

    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用法示例。

        2
  •  4
  •   Seamus Abshere    14 年前

    基于Evangineeur的答案,这里是Corban的答案,如果你有Ruby1.9:

    # 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 }
    

    我的公司用它来显示用于碳计算的红宝石代码…我们在Ruby1.8中使用了ParseTree,现在 sourcify with Ruby 1.9 .

        3
  •  2
  •   Evangenieur    14 年前

    在Ruby1.9中,您可以尝试这个从源文件中提取代码的gem。

    https://github.com/ngty/sourcify

        4
  •  2
  •   Nick B    9 年前

    在Ruby1.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!
    

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

    推荐文章