Printing the source code of a Ruby block

前端 未结 4 1039
情书的邮戳
情书的邮戳 2020-12-06 01:33

I have a method that takes a block.

Obviously I don\'t know what is going to be passed in and for bizarre reasons that I won\'t go into here I want to print the cont

4条回答
  •  佛祖请我去吃肉
    2020-12-06 02:19

    In Ruby 1.9+ (tested with 2.1.2), you can use https://github.com/banister/method_source

    Print out the source via 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!
    

    Note that in order for the source to be read you need to use a file and execute the file (testing it out from irb will result in the following error: MethodSource::SourceNotFoundError: Could not load source for : No such file or directory @ rb_sysopen - (irb)

提交回复
热议问题