tags:

views:

146

answers:

2

I have a method that takes a block.

Obviously I don't know what is going to be passed in and for bizarre reasons that I won't go into here I want to print the contents of the block.

Is there a way to do this?

+4  A: 

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%5Fwanstrath.html He shows some interesting ruby2ruby and parsetree usage examples.

Corban Brook
Does this only work with Ruby 1.8? http://blog.zenspider.com/2009/04/parsetree-eol.html talks about "dropping block/proc support" to deal with ParseTree not being available in ruby 1.9.
Andrew Grimm
No this will not work in ruby 1.9 as it doesn't provide the needed hooks for ParseTree to work. Apparently there is noway to get the sexp in 1.9. This is not a huge problem because by the time everyone makes the switch to 1.9 other vms like rubinius should be available for prime time. Rubinius natively includes a to_sexp for all objects so it will be trivial to do these sort of operations.
Corban Brook
+1  A: 

There is no way to do this in Ruby 1.9.

Ken Bloom