Reason #32 • February 1st, 2026

String#lines

A very common operation is to split a string into lines. In Ruby, this is made easy with the String#lines method:

Ruby
linux_style = "Hello\nWorld\nRuby".lines
# => ["Hello\n", "World\n", "Ruby"]

windows_style = "Hello\r\nWorld\r\nRuby".lines
# => ["Hello\r\n", "World\r\n", "Ruby"]
      
JavaScript
const linesRegexp = /[^\n]*\n|[^\n]+$/g
const linux_style = "Hello\nWorld\nRuby".match(linesRegexp);
// => ["Hello\n", "World\n", "Ruby"]

const windows_style = "Hello\r\nWorld\r\nRuby".match(linesRegexp);
// => ["Hello\r\n", "World\r\n", "Ruby"]
      

If we want the lines without trailing newlines, we can pass the chomp: true option:

Ruby
linux_style = "Hello\nWorld\nRuby".lines(chomp: true)
# => ["Hello", "World", "Ruby"]

windows_style = "Hello\r\nWorld\r\nRuby".lines(chomp: true)
# => ["Hello", "World", "Ruby"]
      
JavaScript
function chompedLines(s) {
  const chunks = s.match(/[^\n]*\r?\n|[^\n]+$/g) ?? [];
  return chunks.map(line => line.replace(/\r?\n$/, ""));
}

const linux_style = chompedLines("Hello\nWorld\nRuby");
// => ["Hello", "World", "Ruby"]

const windows_style = chompedLines("Hello\r\nWorld\r\nRuby");
// => ["Hello", "World", "Ruby"]
      

Very handy!

History

The String#lines method was added to Ruby in version 1.9, released on Christmas 2007. The chomp: true option was added in version 2.4, released on Christmas 2016.

Thus ends the first String week at Loving Ruby. I hope you enjoyed it! ❤️

Reason #33 ?