tags:

views:

36

answers:

2

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.

+2  A: 

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.

Nikita Rybak
+1  A: 

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
AboutRuby