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.
57e7d6a3118e1943b7843d1c372d4b3b?d=identicon&s=25 stephan.zimmer (Guest)
on 2008-10-08 10: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
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2008-10-08 11:01
(Received via mailing list)
2008/10/8 stephan.zimmer <stephan.zimmer@googlemail.com>:
> 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
Fc8263f8baca7a7b76605cfdd0c4afa2?d=identicon&s=25 Ragav Satish (ragav)
on 2008-10-08 17: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.