All posts

How to iterate a string containing newlines in Ruby

 ruby

Let’s say you have a string that resembles "a string that \n is really multiple paragraphs \n" and you want to work with each section of the string with a newline, Ruby has a method to handle that called each_line.

paragraph = []
example_paragraph = "a string that \n is really multiple paragraphs \n"
example_paragraph.each_line do |line|
  paragraph << line
end

=> paragraph
["a string that \n", " is really multiple paragraphs \n"]

It can also iterate over the string any time it encounters a substring passed to it:

paragraph = []
example_paragraph = "a string that \n is really multiple paragraphs \n"
example_paragraph.each_line("really") do |line|
  paragraph << line
end

=> paragraph
["a string that \n is really", " multiple paragraphs \n"]

Further reading:

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).