how can I read a file, bytes at a time in Ruby?

11,696

Solution 1

Well, that's because no block is given. You can either replace yield buffer with puts buffer (or any operation you want) or create a separate method taking code block:

def read_file
  File.open('textfile.txt') do |file|
    while (buffer = file.read(size)) do
      yield buffer
    end
  end
end

and call it like this

read_file do |data|
  // do something with data
  puts data 
end

Add normal parameters (like file name or block size) to read_file, if necessary.

Solution 2

I don't know what you're trying to do with yield there. Yield is something you use inside of a block you're intending to repeatedly call, like an Enumerator. It's much easier to just do something like this.

File.open('test.txt') do|file|
  until file.eof?
    buffer = file.read(10)
    # Do something with buffer
    puts buffer
  end
end
Share:
11,696
CountCet
Author by

CountCet

Updated on June 05, 2022

Comments

  • CountCet
    CountCet almost 2 years

    I want to iteratively read a fixed number of bytes in a file, and return them

    My code is below. I have taken it from an example on the internet

    File.open('textfile.txt') do |file|
      while (buffer = file.read(size)) do
         yield buffer
      end
    end
    

    I get the error no block given.