title: Ruby: How to split a file into multiple files of a given size
body: <p>I want to split a txt file into multiple files where each file contains no more than 5Mb. I know there are tools for this, but I need this for a project and want to do it in Ruby. Also, I prefer to do this with File.open in block context if possible, but I fail miserably :o(</p>
  
  <pre><code>#!/usr/bin/env ruby
  
  require 'pp'
  
  MAX_BYTES = 5_000_000
  
  file_num = 0
  bytes    = 0
  
  File.open("test.txt", 'r') do |data_in|
    File.open("#{file_num}.txt", 'w') do |data_out|
      data_in.each_line do |line|
        data_out.puts line
  
        bytes += line.length
  
        if bytes &gt; MAX_BYTES
          bytes = 0
          file_num += 1
          # next file
        end
      end
    end
  end
  </code></pre>
  
  <p>This work, but I don't think it is elegant. Also, I still wonder if it can be done with File.open in block context only.</p>
  
  <pre><code>#!/usr/bin/env ruby
  
  require 'pp'
  
  MAX_BYTES = 5_000_000
  
  file_num = 0
  bytes    = 0
  
  File.open("test.txt", 'r') do |data_in|
    data_out = File.open("#{file_num}.txt", 'w')
  
    data_in.each_line do |line|
      data_out = File.open("#{file_num}.txt", 'w') unless data_out.respond_to? :write
      data_out.puts line
  
      bytes += line.length
  
      if bytes &gt; MAX_BYTES
        bytes = 0
        file_num += 1
        data_out.close
      end
    end
  
    data_out.close if data_out.respond_to? :close
  end
  </code></pre>
  
  <p>Cheers,</p>
  
  <p>Martin</p>