Skip to content
instance method

String#lines

(?::string? separator, ?chomp: ::boolish) -> ::Array[::String]
(?::string? separator, ?chomp: ::boolish) { (::String line) -> void } -> self
lines(record_separator = $/, chomp: false) → array_of_strings

Returns substrings (“lines”) of self according to the given arguments:

Example
s = <<~EOT
This is the first line.
This is line two.

This is line four.
This is line five.
EOT

With the default argument values:

Example
$/ # => "\n"
s.lines
# =>
["This is the first line.\n",
 "This is line two.\n",
 "\n",
 "This is line four.\n",
 "This is line five.\n"]

With a different record_separator:

Example
record_separator = ' is '
s.lines(record_separator)
# =>
["This is ",
 "the first line.\nThis is ",
 "line two.\n\nThis is ",
 "line four.\nThis is ",
 "line five.\n"]

With keyword argument chomp as true, removes the trailing newline from each line:

Example
s.lines(chomp: true)
# =>
["This is the first line.",
 "This is line two.",
 "",
 "This is line four.",
 "This is line five."]

Related: see Converting to Non-String.

See also #length #ljust #intern #lstrip also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0