Accessing source code of a block

S

stephan.zimmer

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
 
R

Robert Klemme

2008/10/8 stephan.zimmer said:
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"?

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

Cheers

robert
 
R

Ragav Satish

stephan.zimmer said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top