Skip to content

Instantly share code, notes, and snippets.

@jschank
Created October 14, 2012 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jschank/3889529 to your computer and use it in GitHub Desktop.
Save jschank/3889529 to your computer and use it in GitHub Desktop.
Text wrapping method
def wrap_text(text, width, indent_width)
raise ArgumentError.new("Width must be at least 1 character wide.") if width <= 1
raise ArgumentError.new("Wrapping width must be greater than the indent amount.") if width <= indent_width
width -= indent_width
lines = []
curline = nil
text.split.each do |word|
if (curline == nil)
# start a new line
curline = ""
curline << word << " "
elsif (curline.length + word.length <= width)
# add the word to the line we're building
curline << word << " "
else
lines << curline
curline = nil
redo
end
end
lines << curline if curline
lines.join("\n")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment