How to See the Ruby Code in a Proc

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

Take a look at the sourcify gem:

proc { x + y }.to_source
# >> "proc { (x + y) }"

How to extract the code from a Proc object?

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.

Print the actual Ruby code of a block?

This question is related to:

  • Converting Proc and Method to String
  • How to extract the code from a Proc object?
  • Ruby block to string instead of executing
  • Compare the Content, Not the Results, of Procs

as Andrew suggested me when I asked the first one in this list. By using the gem 'sourcify', you can get something close to the block, but not exactly the same:

require 'sourcify'

def block_to_s(&blk)
blk.to_source(:strip_enclosure => true)
end

puts block_to_s {
str = "Hello"
str.reverse!
print str
}

In above, notice that you either have to put parentheses around the argument of puts (block_to_s ... end) or use {...} instead of do ... end because of the strength of connectivity as discussed repeatedly in stackoverflow.

This will give you:

str = "Hello"
str.reverse!
print(str)

which is equivalent to the original block as a ruby script, but not the exact same string.

Printing the source code of a Ruby block

You can do this with Ruby2Ruby which implements a to_ruby method.

require 'rubygems'
require 'parse_tree'
require 'parse_tree_extensions'
require 'ruby2ruby'

def meth &block
puts block.to_ruby
end

meth { some code }

will output:

"proc { some(code) }"

I would also check out this awesome talk by Chris Wanstrath of Github http://goruco2008.confreaks.com/03_wanstrath.html He shows some interesting ruby2ruby and parsetree usage examples.



Related Topics



Leave a reply



Submit