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

后端 未结 5 1027
别那么骄傲
别那么骄傲 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:16

    If proc is defined into a file, U can get the file location of proc then serialize it, then after deserialize use the location to get back to the proc again

    proc_location_array = proc.source_location

    after deserialize:

    file_name = proc_location_array[0]

    line_number = proc_location_array[1]

    proc_line_code = IO.readlines(file_name)[line_number - 1]

    proc_hash_string = proc_line_code[proc_line_code.index("{")..proc_line_code.length]

    proc = eval("lambda #{proc_hash_string}")

提交回复
热议问题