20

Given a Proc object, is it possible to look at the code inside it?

For example:

p = Proc.new{test = 0}

What I need is for some way to get the string "test = 0" from a Proc object that has already been created.

juan2raid
  • 1,606
  • 1
  • 18
  • 29

4 Answers4

15

You can use the ruby2ruby library:

>> # tested with 1.8.7
>> require "parse_tree"
=> true
>> require "ruby2ruby"
=> true
>> require "parse_tree_extensions"
=> true
>> p = Proc.new{test = 0}
>> p.to_ruby
=> "proc { test = 0 }"

You can also turn this string representation of the proc back to ruby and call it:

>> eval(p.to_ruby).call
0

More about ruby2ruby in this video: Hacking with ruby2ruby.

riffraff
  • 2,429
  • 1
  • 23
  • 32
miku
  • 181,842
  • 47
  • 306
  • 310
13

In case you're using Ruby 1.9, you can use the sourcify gem

$ irb
ruby-1.9.2-p0 > require 'sourcify'
             => true 
ruby-1.9.2-p0 > p = Proc.new{test = 0}
             => #<Proc:0xa4b166c@(irb):2> 
ruby-1.9.2-p0 > p.to_source
             => "proc { test = 0 }" 
Seamus Abshere
  • 8,326
  • 4
  • 44
  • 61
  • 4
    The sourcify gem is now unmaintained: https://github.com/ngty/sourcify/issues/34#issuecomment-75375440 – Gerry May 04 '15 at 02:55
12

Use proc.source_location to get the location of the source file that defines the proc. It also returns the line number of the definition. You can use those values to locate the location of the proc source.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Reza
  • 1,478
  • 1
  • 15
  • 25
  • This isn't literally an answer to this question. However, it's helped me debug a problem like this where the proc wasn't coming from where I thought it was. So +1 for that. – AJFaraday Feb 17 '16 at 16:27
2

I think you could use ParseTree for this, it also seems that support for Ruby 1.9.2 is getting close.

Sam Saffron
  • 128,308
  • 78
  • 326
  • 506