Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

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. Strings provide an iterator, each_line, to process a string one line at a time:

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

The preceding code produces three lines of output:

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

Iterators (such as each_line) can be chained together with other iterators (such as with_index). Connecting function outputs and inputs in a line like this is a technique sometimes called function composition (or method chaining). Instead of tracking the line number manually, with_index can be composed with each_line to produce the exact same output:

str = "Once upon\na time...\nThe End\n"
str.each_line.with_index do |line, num|
  print "Line #{num + 1}: #{line}"
  • + Share This
  • 🔖 Save To Your Account