Forum: Ruby Accessing source code of a block

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
stephan.zimmer (Guest)
on 2008-10-08 12:35
(Received via mailing list)
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
Robert K. (Guest)
on 2008-10-08 13:01
(Received via mailing list)
2008/10/8 stephan.zimmer <removed_email_address@domain.invalid>:
> 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
Ragav S. (Guest)
on 2008-10-08 19:00
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
This topic is locked and can not be replied to.