October 2006
Intermediate to advanced
888 pages
16h 55m
English
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}"
endThe 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.
Read now
Unlock full access