read(p1 = v1, p2 = v2) public

Reads length bytes from the I/O stream.

length must be a non-negative integer or nil.

If length is a positive integer, it try to read length bytes without any conversion (binary mode). It returns nil or a string whose length is 1 to length bytes. nil means it met EOF at beginning. The 1 to length-1 bytes string means it met EOF after reading the result. The length bytes string means it doesn’t meet EOF. The resulted string is always ASCII-8BIT encoding.

If length is omitted or is nil, it reads until EOF and the encoding conversion is applied. It returns a string even if EOF is met at beginning.

If length is zero, it returns “”.

If the optional buffer argument is present, it must reference a String, which will receive the data.

At end of file, it returns nil or “” depend on length. and returns “”. returns nil.

f ="testfile")   #=> "This is line one"

# reads whole file
open("file") {|f|
  data = # This returns a string even if the file is empty.

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

# iterate over variable length records.
# record is prefixed by 32-bit length.
open("variable-record-file") {|f|
  while len =
    len = len.unpack("N")[0] # 32-bit length
    record = # This returns a string even if len is 0.

Note that this method behaves like fread() function in C. If you need the behavior like read(2) system call, consider readpartial, read_nonblock and sysread.

Show source
Register or log in to add new notes.