Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Pathname#read

(?::Integer length, ?::Integer offset, ?mode: ::Integer | ::String, ?flags: ::Integer, ?external_encoding: ::encoding, ?internal_encoding: ::encoding, ?encoding: ::encoding, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish) -> ::String
read(length = nil, offset = 0, **opts) → string or nil

Reads and returns some or all of the content of the file whose path is self.to_s.

With no arguments given, reads in text mode and returns the entire content of the file:

Example
Pathname.new('t.txt').read
# => "First line\nSecond line\n\nFourth line\nFifth line\n"
Pathname.new('t.ja').read
# => "こんにちは"
Pathname.new('t.dat').read
# => "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"

On Windows, text mode can terminate reading and leave bytes in the file unread when encountering certain special bytes. Consider using binread if all bytes in the file should be read.

With argument length given, returns length bytes if available:

Example
Pathname.new('t.txt').read(7)
# => "First l"
Pathname.new('t.ja').read(7)
# => "\xE3\x81\x93\xE3\x82\x93\xE3"
Pathname.new('t.dat').read(7)
# => "\xFE\xFF\x99\x90\x99\x91\x99"

Returns all bytes if length is larger than the files size:

Example
Pathname.new('t.txt').read(700)
# => "First line\r\nSecond line\r\n\r\nFourth line\r\nFifth line\r\n"
Pathname.new('t.ja').read(700)
# => "\xE3\x81\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1\xE3\x81\xAF"
Pathname.new('t.dat').read(700)
# => "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"

With arguments length and offset given, returns length bytes if available, beginning at the given offset:

Example
Pathname.new('t.txt').read(10, 2)
# => "rst line\r\n"
Pathname.new('t.ja').read(10, 2)
# => "\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1"
Pathname.new('t.dat').read(10, 2)
# => "\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"

Returns nil if offset is past the end of the file:

Example
Pathname.new('t.txt').read(10, 200) # => nil

Optional keyword arguments opts specify:

See also #pipe? #readable? #parent #readable_real? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0