# Nested blocks

**URL:** <https://www.ruby-forum.com/t/nested-blocks/118428>\
**Category:** Ruby\
**Created:** [October 26, 2007, 8:08pm UTC](https://www.ruby-forum.com/t/nested-blocks/118428 "2007-10-26T20:08:30Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![randy\_k](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/258eb7/32.png) [@randy\_k](https://www.ruby-forum.com/u/randy_k)\
**Post date:** [October 26, 2007, 8:08pm UTC](https://www.ruby-forum.com/t/nested-blocks/118428/1 "2007-10-26T20:08:30Z")

</div>

Recently I’ve written several small utilities which are basically  
filters–they read a file one line at a time, do something with one or  
more  
of those lines, and write one or more lines to an output file.

(With help at various times from the list) I got those utilities working  
with  
a nested block structure something like this:

File.open(“output file”, “w”) do |f|  
File.open(“input file”).each do |line|  
do stuff  
end  
end

For the next somewhat similar utility, that won’t work as well–I really  
want  
to nest the blocks the other way (at least I think so ;-).

The difference (in required functionality) is that this time I need to  
split  
the single input file into multiple output files (multiple entire  
records (of  
varying size) not exceeding a specified maximum file size).

I can see how to do it something like this (beware the pseudo-code /  
handwaving):

output\_file\_size = 0  
f = File.open(“output file”)  
File.for each(“input\_file”, rec\_sep) do |record|  
if output\_file\_size + record.length \<= max\_file\_size then  
puts f.record  
output\_file\_size = output\_file\_size + record.length  
else  
f.close  
construct next output file name  
output\_file\_size = 0  
f = File.open(next output file)  
end  
f.close  
end

But I wonder if there is a way to do it with a block for the output  
file.

(ignoring an approach using something like the following to write each  
record:

File.open(“output file”).each { |f| f.puts record}

which opens and closes each output file multiple times, once for each  
record  
written.  
)

More specifically, I’m wondering if there is a way to make something  
like this  
work:

create output file name (-1–i.e., one less than desired file name)  
File.for each(“input file”, rec\_sep) do |record|  
increment output file name #pretty sure this is not in the right place  
File.open(“output file”).each do |f|  
if output\_file\_size \>= max\_file\_size then break end  
puts f.record  
end  
end

Randy K.
