Skip to content

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

class method

IO.readlines

IO.readlines(name, sep=$/ [, getline_args, open_args]) → array
IO.readlines(name, limit [, getline_args, open_args]) → array
IO.readlines(name, sep, limit [, getline_args, open_args]) → array
File.readlines(name, sep=$/ [, getline_args, open_args]) → array
File.readlines(name, limit [, getline_args, open_args]) → array
File.readlines(name, sep, limit [, getline_args, open_args]) → array

Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep.

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and its output is returned. Consider to use File.readlines to disable the behavior of subprocess invocation.

Example
a = File.readlines("testfile")
a[0]   #=> "This is line one\n"

b = File.readlines("testfile", chomp: true)
b[0]   #=> "This is line one"

IO.readlines("|ls -a")     #=> [".\n", "..\n", ...]

If the last argument is a hash, it’s the keyword argument to open.

Options for getline

The options hash accepts the following keys:

:chomp

When the optional chomp keyword argument has a true value, \n, \r, and \r\n will be removed from the end of each line.

See also IO.read for details about name and open_args.

See also #readlines .read .select .popen also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0