Section 2.6. Processing a Byte at a Time

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.

The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: