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.

  • For web searches, another way to say this is "inspect the code inside a Proc." – Nathan Long Aug 7 '12 at 12:13
  • It's been a couple years since this question was asked. Anyone know if there have been any recent developments in this area? – Ajedi32 Jan 17 '14 at 17:35
  • more recent answers: stackoverflow.com/a/15024732/109175 ("use sourcify") – Tim Diggins Sep 23 '14 at 15:08
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.

| improve this answer | |
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 }" 
| improve this answer | |
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.

| improve this answer | |
  • 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.

| improve this answer | |
  • 1
    ParseTree reaches EOL with Ruby 1.8. – weakish Nov 30 '14 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.