Search code examples
rubysizebytefixedcontinuations

How to read fixed size of bytes turn by turn in continuation using Ruby?


I have one binary file and I want to read this file like first four bytes then next 5 bytes then next 3 bytes till file ends.

I am able to read file using each_byte but I want to categorize all these bytes in groups in sequence they are stored in file.

I am able to read this using following lines but dont know how to read in fixed sized blocks with continutation.

File.open('myfile','rb') do |file|
file.each_byte {|ch| print "#{ch.chr}:#{ch}\t"}

end


Solution

  • I'm not sure I understand but maybe something like:

    file.read.scan(/(.{4})(.{5})(.{3})/).each do |a,b,c|
        puts "first 4 bytes: #{a}"
        puts "bytes 5 to 10: #{b}"
        puts "3 more bytes: #{c}"
    end