Search code examples
rubystreamblock

ruby each_<size_of_block> equivalent to each_byte


How to read a whole file blockwise in ruby? e.g. megabyte:

files.each do |filename|
    f=File.new(filename)
    f.each_block(1024) {|megabyte|
        print megabyte      
    }
end

I want to use this code in a CGI to merge TS files on the fly while the the user downloads the merged file. With each_byte the download bandwidth is really poor because of the small blocksize (1 byte).


Solution

  • From http://www.ruby-doc.org/core/classes/IO.html#M000918:

    # iterate over fixed length records.
    open("fixed-record-file") {|f|
      while record = f.read(256)
        ...
      end
    }
    

    And you can always wrap it within each-ish method.