2.5. Processing a Line at a Time

A Ruby string can contain newlines. For example, a file can be read into memory and stored in a single string. The default iterator each processes such a string one line at a time:

str = "Once upon\na time...\nThe End\n"
num = 0
str.each do |line|
  num += 1
  print "Line #{num}: #{line}"
end

The preceding code produces three lines of output:

Line 1: Once upon
Line 2: a time...
Line 3: The End

The method each_with_index could also be used in this case.

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.