Accessing source code of a block

Dear all,

say I’m given a function “f” taking a block as argument:

def f(&block)

some code

p “#{block.to_code}”
end

Is there any way to access the source code of the block, i.e. for
calling “f { x+1 }”
the “to_code” function would give back “x+1”?

Stephan

2008/10/8 stephan.zimmer [email protected]:

Is there any way to access the source code of the block, i.e. for
calling “f { x+1 }”
the “to_code” function would give back “x+1”?

No, not out of the box. You would have to use ParseTreee or similar.

Cheers

robert

stephan.zimmer wrote:

Dear all,

say I’m given a function “f” taking a block as argument:

def f(&block)

some code

p “#{block.to_code}”
end

Is there any way to access the source code of the block, i.e. for
calling “f { x+1 }”
the “to_code” function would give back “x+1”?

Stephan

As Robert mentioned there is no way to do this out of the box but you
could use the ruby2ruby gem.

require ‘rubygems’
require ‘ruby2ruby’

def f(&block)
puts block.to_ruby
end

f{|x| x +1} #=> proc { |x| (x + 1) }

While this would give you the code, I’d be reluctant to use this in
anything other than toy programs.

–Cheers
–Ragav