Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

IO#pread

pread(maxlen, offset) → string
pread(maxlen, offset, out_string) → string

Behaves like IO#readpartial, except that it:

  • Reads at the given offset (in bytes).

  • Disregards, and does not modify, the stream’s position (see Position).

  • Bypasses any user space buffering in the stream.

Because this method does not disturb the stream’s state (its position, in particular), pread allows multiple threads and processes to use the same IO object for reading at various offsets.

Example
f = File.open('t.txt')
f.read # => "First line\nSecond line\n\nFourth line\nFifth line\n"
f.pos  # => 52
# Read 12 bytes at offset 0.
f.pread(12, 0) # => "First line\n"
# Read 9 bytes at offset 8.
f.pread(9, 8)  # => "ne\nSecon"
f.close

Not available on some platforms.

See also #pos= #pressed? #pos #print also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0