# Capture code in a block

**URL:** <https://www.ruby-forum.com/t/capture-code-in-a-block/117769>\
**Category:** Ruby\
**Created:** [October 20, 2007, 1:15am UTC](https://www.ruby-forum.com/t/capture-code-in-a-block/117769 "2007-10-20T01:15:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kristoph](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/7cd45c/32.png) [@Kristoph](https://www.ruby-forum.com/u/Kristoph)\
**Post date:** [October 20, 2007, 1:15am UTC](https://www.ruby-forum.com/t/capture-code-in-a-block/117769/1 "2007-10-20T01:15:52Z")

</div>

Greetings,

How might I capture the code in a block so that I can serialize it for  
later use? So for example …

file = CodeFile.new( ‘something.rb’)

file.capture do  
puts ‘Hello World’  
end

… which prompts a file to be created with …

puts ‘Hello World’

Any thoughts how this might be accomplished?

]{

---

<div class="post-metadata">

**Author:** ![Kristoph](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/7cd45c/32.png) [@Kristoph](https://www.ruby-forum.com/u/Kristoph)\
**Post date:** [October 20, 2007, 2:47am UTC](https://www.ruby-forum.com/t/capture-code-in-a-block/117769/2 "2007-10-20T02:47:43Z")

</div>

Quoth Kristoph:

> … which prompts a file to be created with …
> 
> puts ‘Hello World’
> 
> Any thoughts how this might be accomplished?

Do you actually want a literal “puts ‘Hello World’” in the file, or just  
the  
string “Hello World”?

def my\_method &block  
@block = block  
end

def my\_other\_method  
@block.call  
end

Something like that?

HTH,

---

<div class="post-metadata">

**Author:** ![Kristoph](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/7cd45c/32.png) [@Kristoph](https://www.ruby-forum.com/u/Kristoph)\
**Post date:** [October 20, 2007, 7:40pm UTC](https://www.ruby-forum.com/t/capture-code-in-a-block/117769/3 "2007-10-20T19:40:42Z")

</div>

Konrad,

Yes I want to capture and serialize the actual code into a file (and  
not actually execute that code until some later juncture).

Basically I just want the contents of a block as a string, without  
executing it.

Kristoph
