59

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
Rodrigue
  • 3,617
  • 2
  • 37
  • 49
alamodey
  • 14,320
  • 24
  • 86
  • 112

4 Answers4

120

String#each_line

str.each_line do |line|
    #do something with line
end
dfherr
  • 1,633
  • 11
  • 24
21

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.

kch
  • 77,385
  • 46
  • 136
  • 148
4

You can also do with with any pattern:

str.scan(/\w+/) do |w|
  #do something
end
Lolindrath
  • 2,101
  • 14
  • 20
-3
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.

Nick Ryberg
  • 1,134
  • 4
  • 14
  • 20
  • 1
    That won't work. String#each_line without a block returns an Enumerator, which doesn't respond to chomp. Beyond chomp doesn't take a block. – Chuck Mar 02 '09 at 22:48
  • 1
    Something like `str.each_line.map(&:chomp).each do |line|...` would do that, but you might as well do it in the `each_line` iteration as a single pass. – jwadsack Feb 10 '15 at 23:58