# Accessing source code of a block

**URL:** <https://rubytalk.org/t/accessing-source-code-of-a-block/49515>\
**Category:** ruby-talk\
**Created:** [8 October 2008 08:32 UTC](https://rubytalk.org/t/accessing-source-code-of-a-block/49515 "2008-10-08T08:32:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![stephan.zimmer](https://avatars.discourse-cdn.com/v4/letter/s/ecccb3/32.png) [@stephan.zimmer](https://rubytalk.org/u/stephan.zimmer)\
**Post date:** [8 October 2008 08:32 UTC](https://rubytalk.org/t/accessing-source-code-of-a-block/49515/1 "2008-10-08T08:32:59Z")

</div>

Dear all,

say I'm given a function "f" taking a block as argument:

def f(&block)  
&nbsp;&nbsp;# some code

&nbsp;&nbsp;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

---

<div class="post-metadata">

**Author:** ![Robert\_K1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/robert_k1/32/1830_2.png) [@Robert\_K1](https://rubytalk.org/u/Robert_K1)\
**Post date:** [8 October 2008 08:57 UTC](https://rubytalk.org/t/accessing-source-code-of-a-block/49515/2 "2008-10-08T08:57:37Z")

</div>

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

Cheers

robert

> **···**
>
> 2008/10/8 stephan.zimmer \<stephan.zimmer@googlemail.com\>:
> 
> > 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"?
> 
> --  
> remember.guy do |as, often| as.you\_can - without end

---

<div class="post-metadata">

**Author:** ![Ragav\_Satish](https://avatars.discourse-cdn.com/v4/letter/r/91b2a8/32.png) [@Ragav\_Satish](https://rubytalk.org/u/Ragav_Satish)\
**Post date:** [8 October 2008 14:58 UTC](https://rubytalk.org/t/accessing-source-code-of-a-block/49515/3 "2008-10-08T14:58:49Z")

</div>

stephan.zimmer wrote:

> Dear all,
> 
> say I'm given a function "f" taking a block as argument:
> 
> def f(&block)  
> &nbsp;&nbsp;# some code
> 
> &nbsp;&nbsp;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)  
&nbsp;&nbsp;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

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).
