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#readlines

(?::String sep, ?::Integer limit, ?mode: ::Integer | ::String, ?flags: ::Integer, ?external_encoding: ::encoding, ?internal_encoding: ::encoding, ?encoding: ::encoding, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?chomp: ::boolish) -> ::Array[::String]
(::Integer limit, ?mode: ::Integer | ::String, ?flags: ::Integer, ?external_encoding: ::encoding, ?internal_encoding: ::encoding, ?encoding: ::encoding, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?chomp: ::boolish) -> ::Array[::String]
readlines(sep = $/, **options) → array
readlines(limit, **options) → array
readlines(sep, limit, **options) → array

Returns an array of all lines read from the source at the path in self, which must be the path to a file.

Examples here use a file defined at IO Example Files.

With no arguments given, parses lines from the file at the given path, as determined by the default line separator, and returns those lines in an array:

Example
pn = Pathname('t.txt')
ppn.readlines
# => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]

With argument sep given, parses lines as determined by that line separator (see IO Line Separator):

Example
pn.readlines('li')
# => ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]
pn.readlines('')  # Special "paragraphs" separator value.
# => ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
pn.readlines(nil) # Special "slurp" separator value.
# => ["First line\nSecond line\n\nFourth line\nFifth line\n"]

With argument limit given, parses lines as determined by the default line separator and the given line-length limit (see IO Line Separator and IO Line Limit):

Example
pn.readlines(7)
# => ["First l", "ine\n", "Second ", "line\n", "\n", "Fourth ", "line\n", "Fifth l", "ine\n"]

With arguments sep and limit given, combines the two behaviors (see IO Line Separator and Line Limit).

Optional keyword arguments options specify:

See also #readable_real? #readlink #readable? #realdirpath also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0