How do you loop through a multiline string in Ruby?

RubyStringWhile LoopLoops

Ruby Problem Overview


Pretty simple question from a first-time Ruby programmer.

How do you loop through a slab of text in Ruby? Everytime a newline is met, I want to re-start the inner-loop.

def parse(input)
    ...
end

Ruby Solutions


Solution 1 - Ruby

String#each_line

str.each_line do |line|
    #do something with line
end

Solution 2 - Ruby

What Iraimbilanja said.

Or you could split the string at new lines:

str.split(/\r?\n|\r/).each { |line| … }

Beware that each_line keeps the line feed chars, while split eats them.

Note the regex I used here will take care of all three line ending formats. String#each_line separates lines by the optional argument sep_string, which defaults to $/, which itself defaults to "\n" simply.

Lastly, if you want to do more complex string parsing, check out the built-in StringScanner class.

Solution 3 - Ruby

You can also do with with any pattern:

str.scan(/\w+/) do |w|
  #do something
end

Solution 4 - Ruby

str.each_line.chomp do |line|
  # do something with a clean line without line feed characters
end

I think this should take care of the newlines.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalamodeyView Question on Stackoverflow
Solution 1 - RubyIraimbilanjaView Answer on Stackoverflow
Solution 2 - RubykchView Answer on Stackoverflow
Solution 3 - RubyLolindrathView Answer on Stackoverflow
Solution 4 - RubyNick RybergView Answer on Stackoverflow