End of Life Ruby 3.0 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
io.c
View on GitHub ↗
static VALUE
rb_io_s_readlines(int argc, VALUE *argv, VALUE io)
{
VALUE opt;
struct foreach_arg arg;
struct getline_arg garg;
argc = rb_scan_args(argc, argv, "13:", NULL, NULL, NULL, NULL, &opt);
extract_getline_args(argc-1, argv+1, &garg);
open_key_args(io, argc, argv, opt, &arg);
if (NIL_P(arg.io)) return Qnil;
extract_getline_opts(opt, &garg);
check_getline_args(&garg.rs, &garg.limit, garg.io = arg.io);
return rb_ensure(io_s_readlines, (VALUE)&garg, rb_io_close, arg.io);
}
Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep.
Example
a = IO.readlines("testfile") a[0] #=> "This is line one\n" b = IO.readlines("testfile", chomp: true) b[0] #=> "This is line one"
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
chompkeyword argument has a true value,\n,\r, and\r\nwill be removed from the end of each line.
See also IO.read for details about open_args.