# Accessing source code of a block

**URL:** <https://www.ruby-forum.com/t/accessing-source-code-of-a-block/150414>\
**Category:** Ruby\
**Created:** [October 8, 2008, 10:35am UTC](https://www.ruby-forum.com/t/accessing-source-code-of-a-block/150414 "2008-10-08T10:35:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![stephan.zimmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecccb3/32.png) [@stephan.zimmer](https://www.ruby-forum.com/u/stephan.zimmer)\
**Post date:** [October 8, 2008, 10:35am UTC](https://www.ruby-forum.com/t/accessing-source-code-of-a-block/150414/1 "2008-10-08T10:35:27Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![stephan.zimmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecccb3/32.png) [@stephan.zimmer](https://www.ruby-forum.com/u/stephan.zimmer)\
**Post date:** [October 8, 2008, 11:01am UTC](https://www.ruby-forum.com/t/accessing-source-code-of-a-block/150414/2 "2008-10-08T11:01:14Z")

</div>

2008/10/8 stephan.zimmer [removed\_email\_address@domain.invalid](mailto: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

---

<div class="post-metadata">

**Author:** ![stephan.zimmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecccb3/32.png) [@stephan.zimmer](https://www.ruby-forum.com/u/stephan.zimmer)\
**Post date:** [October 8, 2008, 5:00pm UTC](https://www.ruby-forum.com/t/accessing-source-code-of-a-block/150414/3 "2008-10-08T17:00:56Z")

</div>

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
