How to split a string by newline in Ruby

1 Answer

0 votes
# Splits a multi-line string into an array of individual lines.
# Automatically handles cross-platform line endings and strips trailing newlines.
#
# @param text [String] The multi-line string to be split.
# @return [Array<String>] An array containing each line as a clean string.
def split_by_newline(text)
  # Guard clause: return an empty array if the input is nil or empty
  return [] if text.nil? || text.empty?

  # String#lines breaks the text into lines, and chomp: true removes line endings
  text.lines(chomp: true)
end

# --- Example Usage ---

# Sample text containing mixed line endings (Unix LF and Windows CRLF)
multiline_text = "Hello world!\nThis is line two.\r\n\nFinal line here."

# Call the function
result_lines = split_by_newline(multiline_text)

# Print out the parsed lines with their indices
result_lines.each_with_index do |line, index|
  # Usinginspect to clearly show that trailing newlines have been successfully chomped
  puts "Line #{index + 1}: #{line.inspect}"
end


# run:
# 
# Line 1: "Hello world!"
# Line 2: "This is line two."
# Line 3: ""
# Line 4: "Final line here."
# 

 



answered 11 hours ago by avibootz
...