Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

IO#read

read(maxlen = nil) → string or nil
read(maxlen = nil, out_string) → out_string or nil

Reads bytes from the stream (in binary mode):

  • If maxlen is nil, reads all bytes.

  • Otherwise reads maxlen bytes, if available.

  • Otherwise reads all bytes.

Returns a string (either a new string or the given out_string) containing the bytes read. The encoding of the string depends on both maxLen and out_string:

  • maxlen is nil: uses internal encoding of self (regardless of whether out_string was given).

  • maxlen not nil:

    • out_string given: encoding of out_string not modified.

    • out_string not given: ASCII-8BIT is used.

Without Argument out_string

When argument out_string is omitted, the returned value is a new string:

Example
f = File.new('t.txt')
f.read
# => "This is line one.\nThis is the second line.\nThis is the third line.\n"
f.rewind
f.read(40)      # => "This is line one.\r\nThis is the second li"
f.read(40)      # => "ne.\r\nThis is the third line.\r\n"
f.read(40)      # => nil

If maxlen is zero, returns an empty string.

With Argument out_string

When argument out_string is given, the returned value is out_string, whose content is replaced:

Example
f = File.new('t.txt')
s = 'foo'      # => "foo"
f.read(nil, s) # => "This is line one.\nThis is the second line.\nThis is the third line.\n"
s              # => "This is line one.\nThis is the second line.\nThis is the third line.\n"
f.rewind
s = 'bar'
f.read(40, s)  # => "This is line one.\r\nThis is the second li"
s              # => "This is line one.\r\nThis is the second li"
s = 'baz'
f.read(40, s)  # => "ne.\r\nThis is the third line.\r\n"
s              # => "ne.\r\nThis is the third line.\r\n"
s = 'bat'
f.read(40, s)  # => nil
s              # => ""

Note that this method behaves like the fread() function in C. This means it retries to invoke read(2) system calls to read data with the specified maxlen (or until EOF).

This behavior is preserved even if the stream is in non-blocking mode. (This method is non-blocking-flag insensitive as other methods.)

If you need the behavior like a single read(2) system call, consider readpartial, read_nonblock, and sysread.

Ruby version changes

  1. 3.0
See also .read #raw! #readbyte #raw also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0