Section 2.41. Conclusion

2.40. Wrapping Lines of Text

Occasionally we may want to take long text lines and print them within margins of our own choosing. The code fragment shown here accomplishes this, splitting only on word boundaries and honoring tabs (but not honoring backspaces or preserving tabs):

str = <<-EOF   When in the Course of human events it becomes necessary   for one people to dissolve the political bands which have   connected them with another, and to assume among the powers   of the earth the separate and equal station to which the Laws   of Nature and of Nature's God entitle them, a decent respect   for the opinions of mankind requires that they should declare   the causes which impel them to the separation. EOF max = 20 line = 0 out = [""] input = str.gsub(/\n/," ") words = input.split(" ") while input != ""   word = words.shift   break if not word   if out[line].length + word.length > max     out[line].squeeze!(" ")     line += 1     out[line] = ""   end   out[line] << word + " " end out.each {|line| puts line}  # Prints 24 very short lines

The Format library also handles this and similar operations. Search for it online.

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: