Is it possible to see the ruby code in a proc?

后端 未结 5 1043
别那么骄傲
别那么骄傲 2021-02-05 15:52
p = Proc.new{ puts \'ok\' }

Is is possible to see the ruby code in the proc?

inspect returns the memory location:

         


        
5条回答
  •  野性不改
    2021-02-05 16:22

    Do you mean the original source code or its bytecode representation ?

    For the former you may use standard Proc's method source_location

    p.source_location
    => ["test.rb", 21]
    

    and read the appropriate lines of code.

    For the latter it may come handy the RubyVM::InstructionSequence and its class method disassemble:

    irb> RubyVM::InstructionSequence.disasm p
    => "== disasm: 
    =====\n== catch table\n| catch type: redo   st: 0000 ed: 0011 sp: 0000
    cont: 0000\n| catch type: next   st: 0000 ed: 0011 sp: 0000 cont:
    0011\n|------------------------------------------------------------------------\n
    0000 trace            1                                               
    (   1)\n0002 putself          \n0003 putstring        \"ok\"\n0005 
    send             :puts, 1, nil, 8, \n0011 leave            \n"
    

提交回复
热议问题